[Javascript] Array methods in depth - filter

本文介绍如何使用JavaScript中的数组方法如filter、sort等来筛选和排序数组元素。通过一个具体的例子展示了如何根据条件筛选出特定的数组元素,并按特定标准进行排序。

Array filter creates a new array with all elements that pass the test implemented by the provided function. In this lesson we discuss how only a truthy or falsey value is required as the return value to the function, which in turns allows us to be creative in how we perform the filter. We end the lesson by looking at an example showing how chaining multiple array methods together can lead to very nice, declarative code.

 

const lessons = [
    {
        title: 'Javascript Arrays in Depth - join',
        views: 960,
        tags: ['array', 'join']
    },
    {
        title: 'Javascript Arrays in Depth - concat',
        views: 1050,
        tags: ['array', 'concat']
    },
    {
        title: 'Javascript Arrays in Depth - slice',
        views: 2503,
        tags: ['array', 'slice']
    },
    {
        title: 'Javascript Functions in Depth - bind',
        views: 2500,
        tags: ['functions', 'bind']
    }
];

const minViews = 1000;
const searchTerm = 'array';

const filtered = lessons
    .filter(x => x.tags.indexOf(searchTerm) > -1)
    .filter(x => x.views > minViews)
    .sort((a, b) => b.views - a.views)
    .map(x => `  <li>${x.title}</li>`)
    .join('\n');

console.log(`<ul>
${filtered}
</ul>`);

 

转载于:https://www.cnblogs.com/Answer1215/p/5058574.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值