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}]