Home > Net >  array of objects in javascript - remain with the unequals only (not filter the equal ones)
array of objects in javascript - remain with the unequals only (not filter the equal ones)

Time:12-02

The first array -

const arrOne = [1, 1, 2, 3, 4, 6, 6, 7, -7, 8, -8];

The wanted output filter by equality and oppisite equality -

[2, 3, 4]

I saw a-lot of question similar to what I want to do but they always returns the unique as well. example -

const arrOne = [1, 1, 2, 3, 4, 6, 6, 7, -7, 8, -8];

output -

[1, 2, 3, 4, 6, 7, -7, 8, -8]

CodePudding user response:

One way to do it:

const result = arrOne.filter(function(element, index) {
  let reminder = Array.from(arrOne);
  reminder.splice(index, 1);
  return reminder.indexOf(element) == -1 && reminder.indexOf(-element) == -1;
});

Inside the filter callback, the array gets cloned, then the element at the current index removed. And then we simply check whether the element value or its negative are still found among the remaining values.

  • Related