DEV Community

loading...
Cover image for TypeScript / JavaScript - Check if 2 arrays of primitives contain the same values

TypeScript / JavaScript - Check if 2 arrays of primitives contain the same values

shane
惻1 min read

More JavaScript / Typescript tricks

Intro

How to check if an array of primitives contains the exact same values (in any order) in JavaScript (and TypeScript).

This works for primitives and object references but not the values of an object. (look up primitives in JavaScript)

This can be achieved by checking if all items of Array 1 are in Array 2 and if all items of Array 2 are in Array 1

Walkthrough

// array 2 contains every value of Array 1
const array2containsAll = array1.every(value => array2.includes(value));

// array 1 contains every value of Array 2
const array1containsAll = array2.every(value => array1.includes(value));

// if both are true then both arrays contain the same items
if(array1containsAll === true && array2containsAll === true){
  // arrays match
} else {
  // arrays don't match
}
Enter fullscreen mode Exit fullscreen mode

As a JavaScript function

arraysMatch(array1, array2) {
  return (
    array1.every(value => array2.includes(value)) 
    && array2.every(value => array1.includes(value))
  );
}
Enter fullscreen mode Exit fullscreen mode

As a TypeScript function

(TypeScript is for cool kids btw)
TypeScript doesn't have a specific type for primitives so swap out string below for whatever type you require, or any if you don't care too much about type safety.

arraysMatch(array1: Array<string>, array2: Array<string>): boolean {
  return (
    array1.every(value => array2.includes(value)) 
    && array2.every(value => array1.includes(value))
  )
}
Enter fullscreen mode Exit fullscreen mode

Now follow me on twitter plz https://twitter.com/theshanemcgowan

Discussion (3)

Collapse
hbgl profile image
hbgl

It's a clean solution but it scales O(nĀ²) which is pretty bad. There is room for improvement.

Collapse
shane profile image
shane Author

Any suggestions would be greatly appreciated

Collapse
hbgl profile image
hbgl

I don't know the optimal solution but I can give you a hint. You can achieve better scaling by using a Map or by sorting the arrays.