如何检查json数组是否包含Nodejs中的重复值?

时间:2019-05-03 11:12:42

标签: node.js async-await

var values = {[
    { name: 'jerem' },
    { name: 'jio' },
    { name: 'paul' },
    { name: 'jio' }}
];

var valueArr = values.map(function(item){ return item.name });
var isDuplicate = valueArr.some(function(item, idx){ 
    return valueArr.indexOf(item) != idx 
});
console.log(isDuplicate);

如何使用promise all和async编写上述代码?有人可以在这里帮助我

2 个答案:

答案 0 :(得分:0)

有很多解决方案可从数组中查找重复对象

解决方案1:

 var values = [
    { name: 'someName1' },
    { name: 'someName2' },
    { name: 'someName1' },
    { name: 'someName1' }
]

// solution
var hasDuplicate = false;
values.map(v => v.name).sort().sort((a, b) => {
  if (a === b) hasDuplicate = true
})
console.log('hasDuplicate', hasDuplicate)

解决方案2:如果您所处的环境支持ECMA Script 6的Set,则可以使用Array.prototype.some和Set对象,像这样

let seen = new Set();
var hasDuplicates = values.some(function(currentObject) {
    return seen.size === seen.add(currentObject.name).size;
});

答案 1 :(得分:0)

const filtered = values.filter(ele => ele.name == "YOUR_CONDITION");
if(filtered.length > 1){
  // array contains duplicate elements.
}