Purple awn
Purple awn

Reputation: 137

JavaScript: Change all repeated values to 0 in array

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

Upvotes: 3

Views: 188

Answers (4)

Dani
Dani

Reputation: 913

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

Upvotes: 0

Shahnawaz Hossan
Shahnawaz Hossan

Reputation: 2720

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

Upvotes: 0

Majed Badawi
Majed Badawi

Reputation: 28404

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

Upvotes: 2

phi-rakib
phi-rakib

Reputation: 3302

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

Upvotes: 8

Related Questions