Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace duplicate objects from array

I know there are multiple ways to remove duplicates from arrays in javascript, the one i use is

let originalArray = [1, 2, 3, 4, 1, 2, 3, 4]
let uniqueArray = array => [...new Set(array)]
console.log(uniqueArray) -> [1, 2, 3, 4]

what i want is something similar but instead of removing the duplicates, to replace it with whatever string or number i want, like this

console.log(uniqueArray) -> [1, 2, 3, 4, "-", "-", "-", "-"]

this has to work with any order, like

[1, 2, 3, 3, 4, 5, 7, 1, 6]
result -> [1, 2, 3, "-", 4, 5, 7, "-", 6]

i tested this solution

const arr = [1, 2, 3, 1, 2, 3, 2, 2, 3, 4, 5, 5, 12, 1, 23, 4, 1];

const deleteAndInsert = uniqueList => {
  const creds = uniqueList.reduce((acc, val, ind, array) => {
    let { count, res } = acc;
    
    if (array.lastIndexOf(val) === ind) {
      res.push(val);
    } else {
      count++;
    };
    
    return { res, count };
  }, { count: 0, res: [] });
  
  const { res, count } = creds;

  return res.concat(" ".repeat(count).split(" "));
};

console.log(deleteAndInsert(arr));

but only adds it at the end of the uniques, and also, only works with numbers

i want it to work with strings too, like dates as an example

["2021-02-22", "2021-02-23", "2021-02-22", "2021-02-28"]
like image 280
Nicolas Silva Avatar asked Feb 01 '26 02:02

Nicolas Silva


1 Answers

You could still use a Set and check if the value is in the set.

const
    unique = array => array.map((s => v => !s.has(v) && s.add(v) ? v : '-')(new Set));

console.log(...unique([1, 2, 3, 4, 1, 2, 3, 4]));
console.log(...unique([1, 2, 3, 3, 4, 5, 7, 1, 6]));
like image 196
Nina Scholz Avatar answered Feb 03 '26 14:02

Nina Scholz