TransWikia.com

Replace duplicates items in array with different values

Stack Overflow Asked by Mohamed Eshaftri on November 7, 2021

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

3 Answers

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)

Answered by jonatjano on November 7, 2021

This is actually very simple to do by using sets (Set).

const initialArray = [1,1,1,1,2,2,2,3];
const valuesSet = new Set();

const newArray = initialArray.map((value) => {
    if (valuesSet.has(value)) {
        return 'R';
    } else {
        valuesSet.add(value);
        return value;
    }
});

Answered by Ernesto Stifano on November 7, 2021

You could take a closure over a Set and check if the value is already seen or not.

let array = [1, 1, 1, 1, 2, 2, 2, 3],
    result = array.map((seen => v => seen.has(v) ? 'R' : (seen.add(v), v))(new Set));

console.log(...result);

A check previous value approach

let array = [1, 1, 1, 1, 2, 2, 2, 3],
    result = array.map((v, i, { [i - 1]: l }) => l === v ? 'R' : v);

console.log(...result);

Answered by Nina Scholz on November 7, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP