33
25

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-25

##お題
二つの配列の差分を求める。

function diffArray(arr1, arr2) {
//write your code.
}
diffArray(["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]);

##出力結果 例

[1, 2, 3, 5], [1, 2, 3, 4, 5] // [4]
[1, "calf", 3, "piglet"], [1, "calf", 3, 4] // ["piglet", 4]
[], ["snuffleupagus", "cookie monster", "elmo"] // ["snuffleupagus", "cookie monster", "elmo"]
[1, "calf", 3, "piglet"], [7, "filly"] // [1, "calf", 3, "piglet", 7, "filly"]

##使ったもの
indexOf()
for文
if文
push()

##考え方
・newArrを宣言してここに差分を代入する。
・for文にてarr1とarr2を比較して、indexOfが−1になった数値をnewArrにpushする。
for文二つで、arr1にあってarr2にないもの、arr2にあってarr1にないものをそれぞれpushする。
・return newArryで差分を返しておわり。

##コード

function diffArray(arr1, arr2) {
  var newArr = [];
  for(var a = 0 ; a < arr1.length; a++){
    if(arr2.indexOf(arr1[a]) === -1 ){
      newArr.push(arr1[a]);
    }    
  }
  for(var b = 0; b < arr2.length; b++){
    if(arr1.indexOf(arr2[b]) === -1 ){
       newArr.push(arr2[b]);
       }
  }
  return newArr;
}
diffArray(["diorite", "andesite", "grass", "dirt", "pink wool", "dead shrub"], ["diorite", "andesite", "grass", "dirt", "dead shrub"]);

##アロー関数を使ったコード

function diffArray(arr1, arr2) {
   return arr1.concat(arr2)
    .filter(item => !arr1.includes(item) || !arr2.includes(item));
}

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

33
25
5

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
33
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?