Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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];
like image 935
Purple awn Avatar asked Mar 20 '26 22:03

Purple awn


1 Answers

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);
like image 156
phi-rakib Avatar answered Mar 22 '26 12:03

phi-rakib