以下是一个使用JavaScript按照姓名过滤数组中的最新项目的解决方法的示例:
// 原始项目数组
const projects = [
{ name: 'John', date: '2022-01-05' },
{ name: 'Mary', date: '2022-01-07' },
{ name: 'John', date: '2022-01-08' },
{ name: 'Mary', date: '2022-01-09' },
{ name: 'John', date: '2022-01-10' },
];
// 按照姓名过滤并获取最新项目的函数
function filterLatestProjectByName(projects, name) {
const filteredProjects = projects.filter(project => project.name === name);
const sortedProjects = filteredProjects.sort((a, b) => new Date(b.date) - new Date(a.date));
return sortedProjects[0];
}
// 示例用法
const latestJohnProject = filterLatestProjectByName(projects, 'John');
console.log(latestJohnProject); // 输出:{ name: 'John', date: '2022-01-10' }
const latestMaryProject = filterLatestProjectByName(projects, 'Mary');
console.log(latestMaryProject); // 输出:{ name: 'Mary', date: '2022-01-09' }
在上述示例中,我们定义了一个名为filterLatestProjectByName
的函数,该函数接收两个参数:项目数组和姓名。函数首先使用filter
方法过滤出与给定姓名匹配的项目,然后使用sort
方法按照日期对过滤后的项目数组进行降序排序,最后返回排序后数组的第一个项目,即最新的项目。
我们通过调用filterLatestProjectByName
函数并传入示例项目数组和相应的姓名来获取最新的项目,并使用console.log
打印结果。
下一篇:按照姓名和ID搜索记录