2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

js 配列のオブジェクトから一致するペアを返す

Last updated at Posted at 2016-12-29

##お題
配列のオブジェクト(最初の引数)を調べ、一致するプロパティと値のペア(2番目の引数)を持つすべてのオブジェクトを持つ配列を返す関数を作る。

function findPair(collection, source) {
//write your code.
  return arr;
}

findPair([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
//[{ first: "Tybalt", last: "Capulet" }]

##出力結果

findPair([{ "a": 1 }, { "a": 1 }, { "a": 1, "b": 2 }], { "a": 1 }) // [{ "a": 1 }, { "a": 1 }, { "a": 1, "b": 2 }]
findPair([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 }) // [{ "a": 1, "b": 2 }, { "a": 1, "b": 2, "c": 2 }]
findPair([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "c": 2 }) // [{ "a": 1, "b": 2, "c": 2 }]

##使ったもの
Object.keys()
hasOwnProperty()
filter()
every()

##考え方
・obj.keys()をつかって第二引数の配列のプロパティを新しい配列にいれる。
・fliter()で第一引数から第二引数のプロパティをもたない要素を取り除く。
・hasOwnProperty()で第二引数のプロパティを持ち、値が同じオブジェクトを返しておわり
##コード

function findPair(collection, source) {
 var arr = [];
  var keys = Object.keys(source);// ["last"]
  arr = collection.filter(function(obj) {
    return keys.every(function(key) {
      return obj.hasOwnProperty(key) && obj[key] === source[key];
    });
  });
  return arr;
}
findPair([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });

###他にもコードが浮かんだ方、コメントお待ちしております。

2
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?