function test5(arr) {
let age = arr.sort(function(a, b) {
return Object.fromEntries(a).age - Object.fromEntries(b).age
});
// Arrange by young age. it's work well.
let result = [];
let name = age.filter (function (el) {
if(Array.isArray(age[el])){
result.push(firstName.concat(lastName));
}
return result;
});
return name
}
但是底部功能不起作用.. 无法识别“年龄”数组......所以发生了错误......我不知道为什么......
我想做那个,
const avengers = [
[
['firstName', 'Captain'],
['lastName', 'Americano'],
['age', 105],
],
[
['firstName', 'Master'],
['lastName', 'Strange'],
['age', 120],
],
[
['firstName', 'IronyMan'],
['age', 55],
]
]
test5(list);
// -> ['IronyMan','Captain Americano', 'Master Strange']
答案 0 :(得分:1)
正如@Alex 所指出的,使用 sort
(基于年龄)和 map
来提取名称。
const process = (data) =>
data
.sort((a, b) => a[a.length - 1][1] - b[b.length - 1][1])
.map((arr) =>
arr
.slice(0, arr.length - 1)
.map(([, name]) => name)
.join(" ")
);
const avengers = [
[
["firstName", "Captain"],
["lastName", "Americano"],
["age", 105],
],
[
["firstName", "Master"],
["lastName", "Strange"],
["age", 120],
],
[
["firstName", "IronyMan"],
["age", 55],
],
];
console.log(process(avengers))
答案 1 :(得分:1)
这是您尝试过的解决方案。
我检查该对象中是否存在 lastName 和 firstName 属性。因为否则你会得到你的铁人三项的结果 “IronMan undefined”因为他没有姓氏
const avengers = [{
firstName: 'Captain',
lastName: 'Americano',
age: 105,
},
{
firstName: 'Master',
lastName: 'Strange',
age: 120
},
{
firstName: 'IronyMan',
age: 55
}
]
console.log(test5(avengers));
// -> ['IronyMan','Captain Americano', 'Master Strange']
function test5(arr) {
let result = [];
let sortedByAge = arr.sort(compare);
sortedByAge.forEach((x) => {
let name = "";
if(x.firstName !== undefined){
name += x.firstName;
}
if(x.lastName !== undefined){
name += " " + x.lastName;
}
result.push(name)
})
return result;
}
function compare(a, b) {
return a.age - b.age;
}