我很难理解高阶函数。我有一个对象数组,想从以下最旧的列表中返回开发人员。如果有些人的年龄相同,我想将他们全部归还。
let input = [
{ firstName: 'Gabriel', lastName: 'X.', country: 'Monaco', continent: 'Europe', age: 49, language: 'PHP' },
{ firstName: 'Odval', lastName: 'F.', country: 'Mongolia', continent: 'Asia', age: 38, language: 'Python' },
{ firstName: 'Emilija', lastName: 'S.', country: 'Lithuania', continent: 'Europe', age: 19, language: 'Python' },
{ firstName: 'Sou', lastName: 'B.', country: 'Japan', continent: 'Asia', age: 49, language: 'PHP' },
];
我正在寻找的输出:
let output = [
{ firstName: 'Gabriel', lastName: 'X.', country: 'Monaco', continent: 'Europe', age: 49, language: 'PHP' },
{ firstName: 'Sou', lastName: 'B.', country: 'Japan', continent: 'Asia', age: 49, language: 'PHP' },
];
这是我的代码:
let oldDevFirst = input.sort((a,b)=>ages= b.age-a.age)
let allOdldDev = oldDevFirst.filter(el=> el === el.age[0]) //oldest developer at el.age[0]
基本上我用“oldDevFirst”对列表进行排序,以便最老的开发人员排在第一位。但是,我不知道如何将每个属性与第一个属性进行比较以返回所有具有相同年龄的开发人员。感谢阅读甚至帮助初学者!
最佳答案
你需要这样做:
let input = [
{ firstName: 'Gabriel', lastName: 'X.', country: 'Monaco', continent: 'Europe', age: 49, language: 'PHP' },
{ firstName: 'Odval', lastName: 'F.', country: 'Mongolia', continent: 'Asia', age: 38, language: 'Python' },
{ firstName: 'Emilija', lastName: 'S.', country: 'Lithuania', continent: 'Europe', age: 19, language: 'Python' },
{ firstName: 'Sou', lastName: 'B.', country: 'Japan', continent: 'Asia', age: 49, language: 'PHP' },
];
let oldDevFirst = input.sort((a,b)=>ages= b.age-a.age)
let maxAge = oldDevFirst[0].age;
let allOdldDev = oldDevFirst.filter(el=> el.age === maxAge)
console.log(allOdldDev);
更好的方法是找到最高年龄,然后获取列表:
let input = [
{ firstName: 'Gabriel', lastName: 'X.', country: 'Monaco', continent: 'Europe', age: 49, language: 'PHP' },
{ firstName: 'Odval', lastName: 'F.', country: 'Mongolia', continent: 'Asia', age: 38, language: 'Python' },
{ firstName: 'Emilija', lastName: 'S.', country: 'Lithuania', continent: 'Europe', age: 19, language: 'Python' },
{ firstName: 'Sou', lastName: 'B.', country: 'Japan', continent: 'Asia', age: 49, language: 'PHP' },
];
let maxAge = Math.max.apply(Math, input.map(function(o) { return o.age; }))
let allOdldDev = input.filter(el=> el.age === maxAge)
console.log(allOdldDev);
关于javascript - 具有过滤器和排序功能的高阶函数可在对象数组中查找指定属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63719444/