LoginSignup
3
0

More than 3 years have passed since last update.

私が考えるJavascriptでの配列操作ベストプラクティス2019

Last updated at Posted at 2019-07-09

目的と前提

  • 実装するときにいつもひと手間かかってしまうので、配列の比較ロジックの備忘録です。
  • ES2015(ES6)のバージョンを想定。

比較パターン

(1) オブジェクトと配列を比較 → 値が重複するオブジェクトをそのまま取り出す


const array = ["test1", "test2", "test3", "test4"];
const objectArray = [
    {param: "ちがうよ"},
    {param: "ちがうよ"},
    {param: "test1"},
    {param: "ちがうよ"},
    {param: "test2"}
];


const newArray = [];
for (const targetValue of array) {
    const sameValue = objectArray.find(obj => obj.param === targetValue);
    newArray.push(sameValue);
}

console.log(newArray); //[ { param: 'test1' }, { param: 'test2' } ]

(2)オブジェクトと配列を比較 → 値が重複するオブジェクトの値を取り出す


const newValueArray = newArray.map(data => data.param);
console.log(newValueArray);  // [ 'test1', 'test2' ]

(3) 配列どうしを比較 → 重複する値を取り出す


const compareArray = ["test1", "test2"];

const arrayOfDupulicates = array.filter(value => compareArray.includes(value));
console.log(arrayOfDupulicates); //[ 'test1', 'test2' ]

(4) 配列どうしを比較 → 重複しない値を取り出す


const arrayRemovedDupulicates = array.filter(value => !compareArray.includes(value));
console.log(arrayRemovedDupulicates); //[ 'test3', 'test4' ]
3
0
1

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