Home > Net >  how to get the absolute difference in elements between two arrays in Javascript
how to get the absolute difference in elements between two arrays in Javascript

Time:09-02

There are many examples on StackOverflow, but I couldn't find any that handled duplicate values in the way I need.

Given

a=  [a, a, b]
b=   [a, b]

I want the result to be

result = returnAllElementsFromAThatAreNotInB(a,b)
//result = [a]

result = returnAllElementsFromAThatAreNotInB(b,a)
// result = []

or let’s say I have:

a2 = [1, 2, 2, 3, 4, 4]
b2 = [1, 2, 2, 3, 3, 4]

I want to get:

result = returnAllElementsFromAThatAreNotInB(a2,b2)
//console.log(result) = [4]

result = returnAllElementsFromAThatAreNotInB(b2,a2)
//console.log(result) = [3]

the difference and symmetrical difference shown here How to get the difference between two arrays in JavaScript?

don't work. They empty arrays because it's checking only values, not instances of elements... the problem is I care about the number of elements of a value, not just the value.

CodePudding user response:

const uniqueDifference = (added, removed) => {
  if (added.length === 0) return [[], removed]

  const [x, ...xs] = added
  const idx = removed.findIndex(y => x === y)

  if (idx > -1) {
    return uniqueDifference(xs, removed.filter((_, i) => i !== idx))
  }

  const [as, rs] = uniqueDifference(xs, removed)
  return [[x, ...as], rs]
}

CodePudding user response:

You could try to loop through b and apply indexOf with splice on each element.
Minimal working code would look like this:

const diff = (a, b) => {
    //copy array to prevent mutations of inital array
    const temp = [...a]; 
    b.forEach(el => {
        let idx = temp.indexOf(el); //find element in a
        if (idx != -1) temp.splice(idx, 1); //if element found delete them
    });
    return temp;
};
const a = ["a", "a", "b"];
const b = ["a", "b"];
console.log(diff(a,b));

const a2 = [1, 2, 2, 3, 4, 4];
const b2 = [1, 2, 2, 3, 3, 4];

console.log(diff(a2,b2));

CodePudding user response:

This will do it for you.

See Array.splice(), spread syntax (...), and Array.findIndex()

const a = ["a", "a", "b"];
const b = ["a", "b"];

const a2 = [1, 2, 2, 3, 4, 4]
const b2 = [1, 2, 2, 3, 3, 4]



console.log(returnAllElementsFromAThatAreNotInB(a, b));
// [a]

console.log(returnAllElementsFromAThatAreNotInB(b, a));
// []

console.log(returnAllElementsFromAThatAreNotInB(a2,b2));
// [4]

console.log(returnAllElementsFromAThatAreNotInB(b2,a2));
// [3]

function returnAllElementsFromAThatAreNotInB(a, b) {
  const tempA = [...a];
  b.forEach((item) => {
    const matchIndex = tempA.findIndex((tempItem) => tempItem === item);
    if (matchIndex > -1) {
      tempA.splice(matchIndex, 1);
    }
  });

  return tempA
}

  • Related