Search code examples
javascriptarraysloopsreplacelodash

Replace duplicates items in array with different values


i would like to Replace duplicates items with different values.

eg arr = [1,1,1,1,2,2,2,3] i want to replace the duplicates with R

So the result looks like this arr = [1,R,R,R,2,R,R,3]

right now I'm using this approach:

    arr = [1,1,1,1,2,2,2,3]
    let previous = 0;
    let current = 1;
    while (current < arr.length) {
        if (arr[previous] === arr[current]) {
            arr[current] = 'R';
            current += 1;
        } else if (arr[previous] !== arr[current]) {
            previous = current;
            current += 1;
        }
    }

i wondering if there is different approach for to achieve that. for Example using Lodash (uniqwith, uniq).

Thanks


Solution

  • here's how I'd do it It look if the current element is the first of the array with the current value and replace it if not

    It may take some times on very big arrays

    const input = [1,1,1,1,2,2,2,3]
    let output = input.map(
      (el, i) => input.indexOf(el) === i ? el : 'R'
    )
    console.log(output)