3

I have an array with duplicate values

let ary = [5, 1, 3, 5, 7, 8, 9, 9, 2, 1, 6, 4, 3];

I want to set the repeated values to 0:

[0, 0, 0, 0, 7, 8, 0, 0, 2, 0, 6, 4, 0]

can find out the repeated value, but I want to change the repeated value to 0, is there any better way?

let ary = [5, 1, 3, 5, 7, 8, 9, 9, 2, 1, 6, 4, 3];

Array.prototype.duplicate = function () {
  let tmp = [];
  this.concat().sort().sort(function (a, b) {
    if (a == b && tmp.indexOf(a) === -1) tmp.push(a);
  });
  return tmp;
}

console.log(ary.duplicate()); // [ 1, 3, 5, 9 ]

// ? ary = [0, 0, 0, 0, 7, 8, 0, 0, 2, 0, 6, 4, 0];

5
  • 2
    What is your question here? How to implement this? Commented Dec 27, 2020 at 9:10
  • 1
    your example does not fit your explaination... why all the randomly indexed zeros? Commented Dec 27, 2020 at 9:14
  • please elaborate your question. Commented Dec 27, 2020 at 9:15
  • @adirabargil It's all items that are non-unique that are set to zero. Commented Dec 27, 2020 at 9:19
  • so why 7 not zero? Commented Dec 27, 2020 at 9:22

4 Answers 4

8

You could use indexOf() and lastIndexOf() method to solve your problem.

const array = [5, 1, 3, 5, 7, 8, 9, 9, 2, 1, 6, 4, 3];
const ret = array.map((x) =>
  array.indexOf(x) !== array.lastIndexOf(x) ? 0 : x
);
console.log(ret);

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

Comments

2

const ary = [5, 1, 3, 5, 7, 8, 9, 9, 2, 1, 6, 4, 3];

// get set of duplicates
let duplicates = ary.filter((elem, index, arr) => arr.indexOf(elem) !== index)
duplicates = new Set(duplicates); 

// set duplicate elements to 0
const res = ary.map(e => duplicates.has(e) ? 0 : e);

console.log(...res);

Comments

0

First, count values and store them in an object. Then loop over the array and check from that stored object whether the count of specific value is greater than 1 or not, if greater than 1, set that to 0. Here is the working example:

let ary = [5, 1, 3, 5, 7, 8, 9, 9, 2, 1, 6, 4, 3];

let countValue = {}, len = ary.length;

for (i = 0; i < len; i++) {
    if (countValue[ary[i]]) {
        countValue[ary[i]] += 1;
    } else {
        countValue[ary[i]] = 1;
    }
}

for (i = 0; i < len; i++) {
    if (countValue[ary[i]] > 1) {
        ary[i] = 0;
    }
}

console.log(...ary);

Comments

0

Probably this is the quickest algorithm, though it will alter your original array.

const array = [5, 1, 3, 5, 7, 8, 9, 9, 2, 1, 6, 4, 3];
const map = {};
for (let ind = 0; ind < array.length; ind++) {
  const e = array[ind];
  if (map[e] === undefined) {
    map[e] = ind;
  } else {
    array[map[e]] = 0;
    array[ind] = 0;
  }
}
console.log(...array);

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.