[Javascript] Array methods in depth - filter

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>`);
上一篇:Dictionary 总结


下一篇:net start/stop mysql access denied.拒绝访问