Yegor
Yegor

Reputation: 3950

Best way to check if values of two arrays are the same/equal in JavaScript

What is the best way to check if two arrays have the same/equal values (in any order) in JavaScript?

These values are just a primary keys of database entities, so they always will be different

const result = [1, 3, 8, 77]
const same = [8, 3, 1, 77]
const diff = [8, 3, 5, 77]

areValuesTheSame(result, same) // true
areValuesTheSame(result, diff) // false

How should areValuesTheSame method look like?

P.S. This question looks like a duplicate but I didn't find anything relative to Javascript.

Upvotes: 0

Views: 722

Answers (3)

Ghoul Ahmed
Ghoul Ahmed

Reputation: 4806

Try this:

const result = [1, 3, 8, 77]
const same = [8, 3, 1, 77]
const diff = [8, 3, 5, 77]
const areValuesTheSame = (a,b) => (a.length === b.length) && Object.keys(a.sort()).every(i=>a[i] === b.sort()[i])


console.log(areValuesTheSame(result, same)) // true
console.log(areValuesTheSame(result, diff)) // false

Upvotes: 1

melpomene
melpomene

Reputation: 85767

I'm making the following assumptions:

  • The arrays only contain numbers.
  • You don't care about the order of the elements; rearranging the arrays is OK.

Under those conditions we can simply convert each array to a canonical string by sorting it and joining the elements with e.g. a space. Then (multi-)set equality boils down to simple string equality.

function areValuesTheSame(a, b) {
    return a.sort().join(' ') === b.sort().join(' ');
}

const result = [1, 3, 8, 77];
const same = [8, 3, 1, 77];
const diff = [8, 3, 5, 77];

console.log(areValuesTheSame(result, same));
console.log(areValuesTheSame(result, diff));

This is probably the laziest / shortest approach.

Upvotes: 3

Nina Scholz
Nina Scholz

Reputation: 386604

You could count all elements with a Map (this is type save) up for the one array and down for the other and check if all items have a final count of zero.

function haveSameValues(a, b) {
    const count = d => (m, v) => m.set(v, (m.get(v) || 0) + d)
    return Array
        .from(b.reduce(count(-1), a.reduce(count(1), new Map)).values())
        .every(v => v === 0);
}

const result = [1, 3, 8, 77]
const same = [8, 3, 1, 77]
const diff = [8, 3, 5, 77]

console.log(haveSameValues(result, same)); // true
console.log(haveSameValues(result, diff)); // false

Upvotes: 2

Related Questions