How to remove common values of first array from second in JavaScript?

Total
0
Shares

Suppose you have an array and you want to remove values from it which are common in second array, then you can use _.difference(array, [values]) function of Lodash.

Let’s see how it works –

[a, b, c, d] - [e, f, a] = [b, c, d]

This function only returns the elements from first array. It compares the values for equality.

So, if there is an object or array as value then it won’t be able to remove that. Because arrays and objects are recognized by their memory addresses.

Two arrays of same values have different memory addresses. Something like this –

[[a], {b: 1}, c] - [[a], {b: 1}, c] = [[a], {b: 1}]

Code Example

1. Using Javascript & Lodash

const firstArray = [1, 2, 3, 4, 5]
const secondArray = [5, 6, 7, 2]

console.log(_.difference(firstArray, secondArray))
// Output 👉 [1, 3, 4]

2. Using ReactJS & Lodash

import _ from "lodash";

export default function App() {
  
  const firstArray = [1, 2, 3, 4, 5, ['a'], {b: 4}]
  const secondArray = [5, 6, 7, 2, ['a'], {b: 4}]

  return <pre>{JSON.stringify(_.difference(firstArray, secondArray))}</pre>;
}

// Output 👉 [1,3,4,["a"],{"b":4}]

Live Demo

Open Live Demo