像年龄这样的对象数组有5条记录,基于sno我们想要第一个元素。
var ages=[
{name: "Jan", age: "90", sno: "1"},
{name: "Harry", age: "100", sno: "1"},
{name: "Tan", age: "10", sno: "2"},
{name: "Ron", age: "15", sno: "2"},
{name: "Roh", age: "19", sno: "2"},
]
输出:
[
{name: "Jan", age: "90", sno: "1"},
{name: "Tan", age: "10", sno: "2"},
]
我试图通过使用ES6 Javascript表达式解决这个问题,通过获取重复的sno,循环通过distinc sno并获取第一个元素。但我需要一个更好的方法。
是否可以在不使用任何内置函数的情况下实现它?
答案 0 :(得分:1)
将Array.filter()
与Set一起使用。在每次迭代时检查Set中是否存在sno
。如果是,则返回false
(删除项目),如果它没有添加到Set,并返回对Set的引用(将被转换为'true')。
var ages = [{"name":"Jan","age":"90","sno":"1"},{"name":"Harry","age":"100","sno":"1"},{"name":"Tan","age":"10","sno":"2"},{"name":"Ron","age":"15","sno":"2"},{"name":"Roh","age":"19","sno":"2"}]
var result = ages.filter(function({ sno }) {
return this.has(sno) ? false : this.add(sno)
}, new Set())
console.log(result)

你可以使用for循环和辅助对象做同样的事情:
var ages = [{"name":"Jan","age":"90","sno":"1"},{"name":"Harry","age":"100","sno":"1"},{"name":"Tan","age":"10","sno":"2"},{"name":"Ron","age":"15","sno":"2"},{"name":"Roh","age":"19","sno":"2"}]
var result = []
var helper = {}
var key
for(var i = 0; i < ages.length; i++) {
item = ages[i]
if(!helper[item.sno]) {
helper[item.sno] = true
result.push(item)
}
}
console.log(result)
&#13;
答案 1 :(得分:0)
您可以使用Set
作为闭包,只过滤未知的sno
。
var ages = [{ name: "Jan", age: "90", sno: "1" }, { name: "Harry", age: "100", sno: "1" }, { name: "Tan", age: "10", sno: "2" }, { name: "Ron", age: "15", sno: "2" }, { name: "Roh", age: "19", sno: "2" }],
filtered = ages.filter((s => ({ sno }) => !s.has(sno) && s.add(sno))(new Set));
console.log(filtered);
答案 2 :(得分:0)
通过reduce(由于some
查找而不是非常高效):
const ages =[
{name: "Jan", age: "90", sno: "1"},
{name: "Harry", age: "100", sno: "1"},
{name: "Tan", age: "10", sno: "2"},
{name: "Ron", age: "15", sno: "2"},
{name: "Roh", age: "19", sno: "2"},
];
const result = ages.reduce((acc, x) => {
if (acc.some(e => e.sno == x.sno) == false)
acc.push(x);
return acc;
}, []);
console.log(result);
答案 3 :(得分:0)
晚会。
var mem;
var result = [];
var ages=[
{name: "Jan", age: "90", sno: "1"}
, {name: "Harry", age: "100", sno: "1"}
, {name: "Tan", age: "10", sno: "2"}
, {name: "Ron", age: "15", sno: "2"}
, {name: "Roh", age: "19", sno: "2"}
];
mem = ages[0];
result.push(ages[0]);
for (var i=0; i<ages.length; i++) {
if (mem.sno == ages[i].sno) {
continue;
} else {
mem = ages[i];
result.push(ages[i]);
}
}
console.log(result);
&#13;