How to replace duplicate objects from array

Viewed 735

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"]
4 Answers

This is a very simple approach to the problem:

function uniqueReplace(arr, rep) {
  let res = [];

  for (x of arr) {
    res.push(res.includes(x) ? rep : x);
  }
  
  return res;
}

console.log(...uniqueReplace([1, 2, 3, 4, 1, 2, 3, 4], '-'));
console.log(...uniqueReplace([1, 2, 3, 3, 4, 5, 7, 1, 6], '-'));

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]));

Just create new Array, use 1 set to control which element appeared, if one element appears more than 1, push new one character like '-'

let originalArray = [1, 2, 3, 4, 1, 2, 3, 4];
let newArray = [];
let set = new Set();
for (let i = 0; i < originalArray.length; i++) {
    if(!set.has(originalArray[i])) {
       newArray.push(originalArray[i]);
       set.add(originalArray[i]);
    } else {
     newArray.push('-');
    }
}
console.log(newArray);

You could do it with reduce

const dashDupes = array =>  array.reduce((acc, e) => {
    if(acc.idx[e])
      acc.arr.push('-')
    else{
      acc.arr.push(e);
    }
    acc.idx[e] = true;
    return acc;
  },{idx:{},arr:[]}).arr

console.log(...dashDupes([1, 2, 3, 4, 1, 2, 3, 4]))
console.log(...dashDupes([1, 2, 3, 3, 4, 5, 7, 1, 6]))

Related