我希望将对象的最大键放入Javascript数组中,以下是JSON数组的示例。我尝试使用reduce()ES6函数,但它只会在记录时返回,因此请帮助我获得最大编号。键数组,我还提供了我想要的输出,如果高阶函数(ES6)中的解决方案很好,那么
let arr = [{
key : 1,
name : 'testaa',
dept : 'ggg'
}, {
key : 1,
name : 'testaa',
dept : 'ggg'
}, {
key : 2,
name : 'testaa',
dept : 'ggg'
}, {
key : 2,
name : 'testaa',
dept : 'ggg'
}, {
key : 2,
name : 'testaa',
dept : 'ggg'
}, {
key : 3,
name : 'testaa',
dept : 'ggg'
}, {
key : 3,
name : 'testaa',
dept : 'ggg'
}]
output i want maximum key of array:
arr = [{
key : 3,
name : 'testaa',
dept : 'ggg'
}, {
key : 3,
name : 'testaa',
dept : 'ggg'
}]
我尝试了用reduce函数,但是只得到一条记录
let data = myArray.reduce(function(prev, curr) {
return prev.key > curr.key ? prev : curr;
});
答案 0 :(得分:4)
您可以分两个步骤进行操作:
let arr = [{
key: 1,
name: 'testaa',
dept: 'ggg'
}, {
key: 1,
name: 'testaa',
dept: 'ggg'
}, {
key: 2,
name: 'testaa',
dept: 'ggg'
}, {
key: 2,
name: 'testaa',
dept: 'ggg'
}, {
key: 2,
name: 'testaa',
dept: 'ggg'
}, {
key: 3,
name: 'testaa',
dept: 'ggg'
}, {
key: 3,
name: 'testaa',
dept: 'ggg'
}];
let max = Math.max(...arr.map(item => item.key));
console.log(arr.filter(item => item.key === max));
答案 1 :(得分:3)
您只返回了最后一个更高的键。您必须构建一个包含所有具有较高键的元素的数组。
在我的算法中,我将最高密钥存储在数组中,当遇到一个具有比所存储元素更高的密钥的元素时,我会鞭打该数组并重新创建一个。
const arr = [{
key: 1,
name: 'testaa',
dept: 'ggg'
}, {
key: 1,
name: 'testaa',
dept: 'ggg'
}, {
key: 2,
name: 'testaa',
dept: 'ggg'
}, {
key: 2,
name: 'testaa',
dept: 'ggg'
}, {
key: 2,
name: 'testaa',
dept: 'ggg'
}, {
key: 3,
name: 'testaa',
dept: 'ggg'
}, {
key: 3,
name: 'testaa',
dept: 'ggg'
}];
const higherKey = arr.reduce((tmp, x) => {
if (!tmp.length || tmp[0].key < x.key) {
return [x];
}
if (tmp[0].key === x.key) {
tmp.push(x);
}
return tmp;
}, []);
console.log(higherKey);
答案 2 :(得分:0)
let arr = [{
key : 1,
name : 'testaa',
dept : 'ggg'
}, {
key : 1,
name : 'testaa',
dept : 'ggg'
}, {
key : 3,
name : 'testaa',
dept : 'ggg'
}, {
key : 2,
name : 'testaa',
dept : 'ggg'
}, {
key : 2,
name : 'testaa',
dept : 'ggg'
}, {
key : 8,
name : 'testaa',
dept : 'ggg'
}, {
key : 3,
name : 'testaa',
dept : 'ggg'
}]
let max = arr[0];
let data = arr.forEach(function(curr,index) {
if(max.key < curr.key) {
max = curr;
}
});
result = arr.map((item) => {
return item.key === map.key;
});
console.log(result)
我建议使用两个循环来找出最大密钥,然后过滤这些密钥,复杂度为o(n)
答案 3 :(得分:0)
如果您想使用reduce
,则可以在一次迭代中使用它(它很冗长,可以根据需要进行简化):
let data = arr.reduce(function(acc, curr) {
// If there is not data on the accumulator, add the first element
if (acc.length === 0) {
acc.push(curr);
return acc;
}
// if current key is smaller than the stored one, clear and start a new accumulator
if (acc[0].key < curr.key) {
acc = [];
acc.push(curr);
}
// If key is the same than the stored one, add it to the accumulator
else if(acc[0].key === curr.key) {
acc.push(curr);
}
// Return the accumulator
return acc;
}, []);