0

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

2
  • Keep a set or a map of everything you've encountered and when a duplicate is found, replace it. Commented Jul 21, 2020 at 14:02
  • do you want to replace only the same value in direct neighborhood? Commented Jul 21, 2020 at 14:05

3 Answers 3

2

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)

Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

Your solution is elegant, but I find it very, very hard to read (even with years of experience with JavaScript). I don't know how helpful it could be for someone who is just starting to learn.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.