Since I do not know what title, what is the cause of an exchange of a small group of partners encountered such a demand:
The original words are as follows:
There are two arrays, m = [a, b], n = [{key: a, name: 'tom'}, {key: b, name: 'jerry'}, {key: c, name: 'marry' }, {key: b, name: 'jerry'}], define a variable, let newArry = n.filter ((e) => {}); will be how to achieve, so newArry equal to [{key: a, name : 'tom'}, {key: b, name: 'jerry'}], and the need to re newArry, seek guidance about ideas, thank
See through answers chiefs do not read the article pure water
The first line and a line and demand:
- Deduplication Array
- Returns the first item in the array corresponds to
See this question, my first idea was to use nested loops to traverse, but ES6 give us a lot more convenient syntax and features, such as Array.prototype.map()
, , Array.prototype.filter()
, Array.prototype.reduce()
, Array.prototype.includes()
these api can greatly improve our efficiency to solve the problem, use the method see Getting ES6 MDN or Ruan Yifeng teacher
Deduplication Array
let hash = {};
let newN = n.reduce(function(item, next) {
hash[next.key] ? '' : hash[next.key] = true && item.push(next);
return item
}, [])
复制代码
Find the corresponding item
let newArray = newN.filter(el=>{
if(m.includes(el.key)) {
return el
}
})
复制代码
Complete code:
let m=['a','b'];
let n=[{key:'a', name: 'tom'},{key:'b', name: 'jerry' }, {key:'c', name: 'marry' },{key:'b', name: 'jerry' }];
// 新数组满足两个条件:
//每个元素具有唯一key(先去重)
//查找key与m数组中的元素匹配
let hash = {};
let newN = n.reduce(function(item, next) {
hash[next.key] ? '' : hash[next.key] = true && item.push(next);
return item
}, [])
let newArray = newN.filter(el=>{
if(m.includes(el.key)) {
return el
}
})
console.log(newArray)
//[{key:'a', name: 'tom'},{key:'b', name: 'jerry' }]
复制代码
Water End
Reproduced in: https: //juejin.im/post/5d0bbc0cf265da1b904be871