Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

js 二つの配列の差分を求める

More than 3 years have passed since last update.

お題

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

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));
}

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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away