C
C
crinnyx2021-08-05 18:36:23
JavaScript
crinnyx, 2021-08-05 18:36:23

How to compare arrays out of element order?

JS language, let's say there are two arrays:
1) [1, 2, 3, 4]
2) [2, 4, 3, 1]

how can I compare them for identity not in the order of the elements?
if through the for of, it will be through the order, but how not?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2021-08-05
@0xD34F

function haveSameValues(arr1, arr2) {
  if (arr1.length !== arr2.length) {
    return false;
  }

  const count = new Map();
  arr1.forEach(n => count.set(n, (count.get(n) ?? 0) + 1));
  arr2.forEach(n => count.set(n, (count.get(n) ?? 0) - 1));

  return [...count.values()].every(n => n === 0);
}


haveSameValues(
  [ 'hello, world!!', 0, 0, 0, 1, 1, false, false ],
  [ false, false, 1, 1, 0, 0, 0, 'hello, world!!' ]
) // true

haveSameValues(
  [ 1, 2, 3 ],
  [ 3, 2, 2 ]
) // false

haveSameValues(
  [],
  []
) // true

S
Sergey Sokolov, 2021-08-05
@sergiks

Plan-A : sort before comparison

const areEqual = (arrA, arrB) => {
  if (arrA.length !== arrB.length) return false;
  const a = arrA.slice().sort(), b = arrB.slice().sort();
  return a.every((el, i) => el === b[i]);
}

Plan-B : hash table (value: number of elements with this value). Count in one array, in another, compare: must match. This solution was perfectly implemented in his answer by 0xD34F
Plan-X : remove matches one by one from copies. This option is ineffective. Brought for entertainment.
const areEqual = (arrA, arrB) => {
  if (arrA.length !== arrB.length) return false;
  const a = arrA.slice(), b = arrB.slice();
  while (a.length) {
    const i = b.indexOf(a.pop());
    if (-1 === i) return false;
    b.splice(i, 1);
  }
  return true;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question