DEV Community

Mehul Lakhanpal
Mehul Lakhanpal

Posted on • Originally published at codedrops.tech

4 ways to check if arrays are equal

const oldTags = ["facebook", "twitter", "instagram", "dev.to"];
const newTags = ["dev.to", "twitter", "facebook", "instagram"];

// Method 1: Using .sort() & .join()

const arr1 = oldTags.sort().join();
const arr2 = newTags.sort().join();

console.log("isEqual?", arr1 === arr2);

// Method 2: Using .includes()

let arr1Status = true;
oldTags.forEach((value) => {
  arr1Status = arr1Status && newTags.includes(value);
});

let arr2Status = true;
newTags.forEach((value) => {
  arr2Status = arr2Status && oldTags.includes(value);
});

console.log("isEqual?", arr1Status && arr2Status);

// Method 3: Using .reduce()

let arr1State = oldTags.reduce(
  (acc, value) => acc && newTags.includes(value),
  true
);
let arr2State = newTags.reduce(
  (acc, value) => acc && oldTags.includes(value),
  true
);

console.log("isEqual?", arr1State && arr2State);

// Method 4: Using .isEqual() from Lodash

console.log("isEqual?", _.isEqual(oldTags.sort(), newTags.sort()));
Enter fullscreen mode Exit fullscreen mode

Thanks for reading 💙

Follow @codedrops.tech for more.

InstagramTwitterFacebook

Micro-Learning ● Web Development ● Javascript ● MERN stack ● Javascript

codedrops.tech


Projects

Note Box - A chrome extension to add notes/todos based on URL

File Ops - A VS Code extension to easily tag/alias files & quick switch between files

Top comments (1)

Collapse
 
melfordd profile image
Melford Birakor

Thanks