Skip to content

Instantly share code, notes, and snippets.

@LeeDDHH
Last active July 8, 2023 08:51
Show Gist options
  • Save LeeDDHH/29c19e4d38ac0ca36c6bdeb733530bf2 to your computer and use it in GitHub Desktop.
Save LeeDDHH/29c19e4d38ac0ca36c6bdeb733530bf2 to your computer and use it in GitHub Desktop.
JavaScriptのデータを操作する際、疑問に思ったこと

2つの配列を比較をして片方には存在しない差分を取得する

前提

  • 比較元となる配列は比較先の配列より要素数が多いか等しい

const array1 = [1, 2, 3, 4, 5, 6];
const array2 = [1, 2, 3, 4];


array3 = array1.filter(i => array2.indexOf(i) == -1)
console.log(array3); // [5, 6]

2つの配列を1つにまとめて重複する値を確認する

前提

  • 配列自体の長さが長いと、1つにまとめたあとの処理が重くなる

function getIsDuplicate(arr1, arr2) {
  return [...arr1, ...arr2].filter(item => arr1.includes(item) && arr2.includes(item)).length > 0
}

const idList1 = ['A12345BC', 'B23456AC', 'C34567CD']
const idList2 = ['A67890AC', 'B23546AC', 'C34567CD']
const idList3 = ['A67890AC', 'B23546AC', 'C31567CD']

console.log(getIsDuplicate(idList1, idList2)) // true
console.log(getIsDuplicate(idList1, idList3)) // false

2つの配列を1つにまとめて重複する値のみを取り出す

const arr1 = ['apple', 'pen', 'pineapple']
const arr2 = ['grape', 'meron', 'apple', 'pen'] // appleとpenが重複
const arr1arr2 = [...arr1, ...arr2]

const duplicatedArr = arr1arr2.filter(
  item => arr1.includes(item) && arr2.includes(item)
)

console.log(duplicatedArr) // [ 'apple', 'pen', 'apple', 'pen' ]
console.log(new Set(duplicatedArr)) // Set { 'apple', 'pen' }

配列内の重複した要素を数えてオブジェクトにまとめる

前提

  • 要素名をキーにして、重複した数を値にする

var arr = [0, 1, 1, 1, 1, 3, 3, 5, 0, 7];

var count = arr.reduce(function(prev, current) {
  prev[current] = (prev[current] || 0) + 1;
  return prev;
}, {});

console.log(count);

// 出力結果
// {0: 2, 1: 4, 3: 2, 5: 1, 7: 1}

1つの配列から重複を弾いて新しい配列にする

var a = [1,2,3,3,2,2,5];

// 重複を削除したリスト
var b = a.filter(function (x, i, self) {
  return self.indexOf(x) === i;
});

console.log(b); // [ 1, 2, 3, 5 ]

1つの配列から重複のみを取り出し、新しい配列にする

var a = [1,2,3,3,2,2,5];

// 重複のみをリスト
var c = a.filter(function (x, i, self) {
  return self.indexOf(x) !== self.lastIndexOf(x);
});

console.log(c); // [ 2, 3, 3, 2, 2 ]

1つの配列から重複したユニークな値のみを取り出し、新しい配列にする

var a = [1,2,3,3,2,2,5];

// 重複を検出したものを重複しないでリスト
var d = a.filter(function (x, i, self) {
  return self.indexOf(x) === i && i !== self.lastIndexOf(x);
});

console.log(d); // [ 2, 3 ]

オブジェクト内のキーバリューセットを、個別のオブジェクトにまとめ、配列とする

var obj = {
  "key-1": "value-1",
  "key-2": "value-2",
  "key-3": "value-3"
}

var result = Object.entries(obj).map(([key, value]) => ({[key]: value}))

console.log(result);

/**
[
  {
    "key-1": "value-1"
  },
  {
    "key-2": "value-2"
  },
  {
    "key-3": "value-3"
  }
] 
*/

Mapを使って、オブジェクトの重複を弾いた配列にする

const users = [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}, {"id": 1, "name": "Alice"}, {"id": 1, "name": "Alice"}]

const uniqueUsers = Array.from(
  new Map(users.map((user) => [user.id, user])).values()
);
// uniqueUsers は [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]

キーが同じなオブジェクト同士の値を足し算し、マージした一つのオブジェクトにする

const a = {
  1: 100,
  2: 200,
  3: 300,
};

const b = {
  1: 10,
  2: 20,
  3: 30,
};

const result = Object.keys(a).reduce((acc, value) => {
  acc[value] = a[value] + b[value];
  return acc;
}, {});

console.log(result);
/*
{
 1: 110,
 2: 220,
 3: 330,
};
*/

異なるキーも含まれたオブジェクト同士で、同じキーの値を足し算し、マージした一つのオブジェクトにする

const a = {
  1: 100,
  3: 300,
  4: 400,
};

const b = {
  1: 10,
  3: 30,
  5: 50,
};

const concatKeys = Object.keys(prev).concat(Object.keys(current));
const uniqueKeys = concatKeys.filter(
  (x, i, self) => self.indexOf(x) === i
);
// [1, 3, 4, 5]

const result = uniqueKeys.reduce(
  (acc, value) => {
    const x = a[value] === undefined ? 0 : a[value];
    const y = b[value] === undefined ? 0 : b[value];
    acc[value] = x + y;
    return acc;
  },
  {}
);

console.log(result);
/*
{
 1: 110,
 3: 330,
 4: 400,
 5: 50,
};
*/

要素を比較するための関数を使って並び替える

昇順

let no = [5, 27, 12, 41];

const sortAsc = (first, second) => {
  if (first > second){
    return 1;
  }else if (first < second){
    return -1;
  }else{
    return 0;
  }
}

no.sort(sortAsc);

console.log(no);
// [5, 12, 27, 41]

降順

let word = ['AA', 'CC', 'BB'];

const sortDesc = (first, second) => {
  if (first > second){
    return -1;
  }else if (first < second){
    return 1;
  }else{
    return 0;
  }
}

word.sort(sortDesc);

console.log(word);
// ["CC", "BB", "AA"]

1つの配列から重複していない要素を取得

var a = [1,2,3,3,2,2,5];

const getUniqueValues = ([...array]) => {
  return array.filter((value, index, self) => self.indexOf(value) === self.lastIndexOf(value));
}

// 重複のみをリスト
var c = getUniqueValues(a);

console.log(c); // [ 1, 5 ]

配列の中で重複した値をカウントする

const arr = ['one', 'one', 'one', 'two', 'two', 'three'];

const count = {};

arr.forEach(element => {
  count[element] = (count[element] || 0) + 1;
});

console.log(count); // { one: 3, two: 2, three: 1 }

参考

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment