JavaScript:将数组中的所有重复值更改为 0

时间:2020-12-27 09:09:10

标签: javascript arrays

我有一个包含重复值的数组

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

我想将重复值设置为 0:

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

可以找出重复值,但是我想把重复值改为0,有什么更好的方法吗?

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

4 个答案:

答案 0 :(得分:8)

您可以使用 indexOf()lastIndexOf() 方法来解决您的问题。

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

答案 1 :(得分: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);

答案 2 :(得分:0)

首先,计算值并将它们存储在一个对象中。然后循环遍历数组并从该存储的对象中检查特定值的计数是否大于 1,如果大于 1,则将其设置为 0。这是工作示例:

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

答案 3 :(得分:0)

这可能是最快的算法,尽管它会改变您的原始数组。

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