Javascript :如果数组有重复值,则将受尊重的索引变量值设置为 true



我有一个对象数组,其中可能包含重复的值。

如果这些索引

具有重复值,我希望这些数组索引变量值为 true。

假设我有以下对象数组

let arr = [
    {
        name :'abc',
        age : 20,
    },
    {
        name :'xyz',
        age : 25,
    },
    {
        name :'pqr',
        age : 22,
    },
    {
        name :'abc',
        age : 27,
    },
    {
        name :'abc',
        age : 26,
    },
]

所以有第 3 和第 4 个索引,其名称重复为 0 个索引。我想将 isError 变量设置为 true 第 3 和第 4 个索引,对于其他我想设置为 false 的变量。

任何帮助都会很棒。

谢谢。

使用 Set 存储现有名称,并映射数组。签入 Set(如果存在名称(,并分配给 isError 变量。将当前名称添加到集合中。使用原始内容创建一个新对象,isError

const markDuplicates = arr => {
  const existingIds = new Set();
  
  return arr.map(o => {
    const isError = existingIds.has(o.name)
    
    existingIds.add(o.name)
    
    return { ...o, isError };
  })
}
const arr = [{"name":"abc","age":20},{"name":"xyz","age":25},{"name":"pqr","age":22},{"name":"abc","age":27},{"name":"abc","age":26}]
const result = markDuplicates(arr)
console.log(result)

您可以先对数组进行排序,然后使用 map 。排序后,所有对象将按名称升序排序。然后使用 map 它将返回一个新数组,并在返回时检查当前对象中的name是否与以前的对象相同。如果是这样,则添加一个重复的键并为其分配一个值

 if (index !== 0 && item.name == k[index - 1].name) {

此行省略了对排序数组中第一个对象的检查,因为没有任何东西可以复制上一个对象,item.name == k[index - 1].name正在检查名称是否与以前的对象相同

let arr = [{
    name: 'abc',
    age: 20,
  },
  {
    name: 'xyz',
    age: 25,
  },
  {
    name: 'pqr',
    age: 22,
  },
  {
    name: 'abc',
    age: 27,
  },
  {
    name: 'abc',
    age: 26,
  },
];
let k = arr.sort(function(a, b) {
  return a.name.localeCompare(b.name);
});
let z = k.map(function(item, index) {
  if (index !== 0 && item.name == k[index - 1].name) {
    return {
      name: item.name,
      age: item.age,
      duplicate: true
    }
  } else {
    return {
      name: item.name,
      age: item.age
    }
  }
});
console.log(z)

您可以使用object作为跟踪器,通过name添加密钥,

如果名称在op上已作为键可用,则循环遍历数据,然后将当前元素isError属性更改为true否则op上创建新键并将当前元素isError设置为false

let arr = [{name :'abc',age : 20,},{name :'xyz',age : 25,},{name :'pqr',age : 22,},{name :'abc',age : 27,},{name :'abc',age : 26,},]
let op = {}
arr.forEach( (inp,index) => {
  if( op[inp.name] ){
    inp.isError = true
  } else{
    inp.isError = false
    op[inp.name] = inp
  }
})
console.log(arr)

最新更新