2
0

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.

複数の配列に共通する要素のみを抽出した配列を出力する

Last updated at Posted at 2018-10-17

コード

以下の関数で抽出可能

var getCommonElementsArray = function(){
  var i = 1, j = 0;
  function removeArrayDuplicates(array) {
    return array.filter(function(value, index, self) {
      return self.indexOf(value) === index;
    });
  }
  var cmnElmArray = arguments[0].slice();
  cmnElmArray = removeArrayDuplicates(cmnElmArray);
  var tgtElmArray = [];
  while(i < arguments.length){
    tgtElmArray = arguments[i++].slice();
    j = 0;
    while(j < cmnElmArray.length){
      if(tgtElmArray.indexOf(cmnElmArray[j])>=0){
        j++;
      }else{
        cmnElmArray.splice(j, 1);
      }
    }
  }
  return cmnElmArray;
};

動作例

ChromeのConsoleにて実行・検証

動作例1

関数の基本の動作について確認。
関数の引数に配列を1つ以上入れて実行すると、共通する要素のみ抜き出した配列が返る。

動作検証コード
var array1 = [1,2,3,3,'hogehoge','foo','bar'];
var array2 = [2,1,0,3,'foo'];
console.log('common',getCommonElementsArray(array1,array2));
console.log('array1',array1);
console.log('array2',array2);

動作結果
image.png
2つの配列に共通する要素のみが抜き出された配列がgetCommonElementsArray()によって得られている。
結果として得られる配列内に同一要素は複数入らない。
また、値渡しを行っているので処理終了後、元の配列は加工されていない。

動作例2

扱う配列が3つ以上になっても問題なく動作する

検証用コード
getCommonElementsArray([0,1,2,3,4,5,6,7,8,9,10], [0,2,4,6,8,10], [0,1,2,3,5,8,13,21]);

動作結果
image.png

動作例3

共通する要素がなかった場合、空の配列が返る
image.png

2
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?