如何在JavaScript中获得每个标题和一个数组中的最小数字?
我希望能得到的结果仅保持在每个标题中最低,如下所示,
var result = [["Alex", "morning", 69],
["Terry", "morning", 127],
["Peter", "morning", 269]];
谢谢
var value_array = [["Alex", "morning", 69],
["Alex", "night", 537],
["Terry", "Afternoon", 141],
["Terry", "MidNight", 327],
["Terry", "morning", 127],
["Peter", "morning", 269]];
// I hope to filter each title(value_array[][0]) the lowest number(value_array[][2])
//Like the lowest for Alex(Title) is 69(lowest number).
//And the lowest for Terry(Title) is 127(lowest Number).
//And the lowest for Peter(Title) is 269(lowest Number).
// this is the format I try, but not working
var result = [];
for (var i = 0; i < value_array.length; i++) {
for (var u = 0; u < value_array.length; u++) {
if (value_array[i][0] == value_array[u][0]) {
const numbers_arr = value_array[i][2];
const add_arr = (a, b) => a + b;
result.push(((numbers_arr.reduce(add_arr))/value_array.length).toFixed(0));
}
}
}
您可以使用哈希表来查找重复的名称,然后比较值:
const value_array = [["Alex", "morning", 69], ["Alex", "night", 537], ["Terry", "Afternoon", 141], ["Terry", "MidNight", 327], ["Terry", "morning", 127], ["Peter", "morning", 269]];
const result = [], hash = {};
for(const [name, time, value] of value_array) {
if(hash[name]) {
if(hash[name][2] > value) {
hash[name][1] = time;
hash[name][2] = value;
}
} else {
result.push(hash[name] = [name, time, value]);
}
}
console.log(result);
或者,您可以按名称对数组进行排序,然后按降序值排序,然后筛选出所有重复的名称:
const value_array = [["Alex", "morning", 69], ["Alex", "night", 537], ["Terry", "Afternoon", 141], ["Terry", "MidNight", 327], ["Terry", "morning", 127], ["Peter", "morning", 269]];
value_array.sort(([nameA, , valueA], [nameB, , valueB]) =>
nameA.localeCompare(nameB) ||
valueA - valueB
);
let dupe = "";
const result = value_array.filter(([name]) => name !== dupe && (dupe = name));
console.log(result);
使用reduce函数并创建一个对象,然后使用Object.values从该对象获取值
var value_array = [
["Alex", "morning", 69],
["Alex", "night", 537],
["Terry", "Afternoon", 141],
["Terry", "MidNight", 327],
["Terry", "morning", 127],
["Peter", "morning", 269],
["Peter", "morning", 20]
];
let m = value_array.reduce(function(acc, curr) {
//check if the object has key by name Alex,Peter ..
// if not then create a key by the name and assign the value to it
// Ex {Alex:["Alex", "morning", 69]}
if (acc[curr[0]] === undefined) {
acc[curr[0]] = curr
} else {
// if it has a key then check the number & compare
// if it is less the than the current then replace it
if (acc[curr[0]][2] > curr[2]) {
acc[curr[0]] = curr
}
}
return acc
}, {})
console.log(Object.values(m))