gpt4 book ai didi

javascript - 在数组对象中搜索唯一属性

转载 作者:行者123 更新时间:2023-12-01 03:48:41 24 4
gpt4 key购买 nike

     var name = [ {
firstN: 'Dave',
lastN: 'Mike',
fullName: 'Dave Mike
},
{
firstN: 'Dave',
lastN: 'Pence',
fullName: 'Dave Pence'
},
{
firstN: 'Tom',
lastN: 'Pence',
fullName: 'Tom Pence'
}, {
firstN: 'Meagher',
lastN: 'Pence',
fullName: 'Meagher Pence'
}, {
firstN: 'Surv',
lastN: 'dyal',
fullName: 'Surv dyal
}
................and so on like 100s
]

所以我想找到唯一的名称,以便名称只出现一次

所以我从上面的数据样本中得到的答案应该是 Dave Mike 和 Surv Dyal

为此我只做到了这一点

var list =Object.keys(newList).map( function(key){

var temp_firstName = newList[key].firstName + ','+ key;
var temp_lastName = newList[key].lastName + ','+ key;
console.log( temp_lastName,temp_firstName );

return temp_lastName, temp_firstName;
});

console.log(list);
//console.log(newList);

}

最佳答案

array.map 是错误的使用方法,因为它是一对一的数组转换。您正在寻找的是一种可以 trim 数组的方法,array.filterarray.reduce 以及记录您姓名的临时键值存储已经遇到过。

const names = [{
firstN: 'Dave',
lastN: 'Mike',
fullName: 'Dave Mike'
},
{
firstN: 'Dave',
lastN: 'Pence',
fullName: 'Dave Pence'
},
{
firstN: 'Tom',
lastN: 'Pence',
fullName: 'Tom Pence'
}, {
firstN: 'Meagher',
lastN: 'Pence',
fullName: 'Meagher Pence'
}, {
firstN: 'Surv',
lastN: 'dyal',
fullName: 'Surv dyal'
}
]

const fn = {};
const ln = {};

const uniqueNames = names.filter(name => {
// Check if it already exists.
const wasVisited = Boolean(fn[name.firstN]) || Boolean(ln[name.lastN]);

// Record the visit:
fn[name.firstN] = ln[name.lastN] = true;

// return the verdict
return !wasVisited;
});

console.log(uniqueNames)

关于javascript - 在数组对象中搜索唯一属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43381945/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com