[英]Javascript filter array based on another array of object
I am trying to merge the two arrays based on Arr1
values.我正在尝试根据
Arr1
值合并两个 arrays 。 If the array 2 doesn't has the respective value in array1
, it should return as empty object with values.如果数组 2 在
array1
中没有相应的值,它应该返回为空的 object 值。 Below are the two arrays:下面是两个arrays:
Arr1 = [{
name: "raj",
age: 20
}, {
name: "ravi",
age: 40
}];
Arr2 = ['raj', 'ravi', 'arnold'];
Javascript Code is, Javascript 代码为,
let result = Arr1.filter(o1 => Arr2.some(o2 => o2 === o1.name));
I am getting the result as below,我得到的结果如下,
result = [{
name: "raj",
age: 20
}, {
name: "ravi",
age: 40
}];
But expected array should be,但预期的数组应该是,
[{
name: "raj",
age: 20
}, {
name: "ravi",
age: 40
}, {
name: "arnold",
age: null,
available: no
}];
Any suggestions?有什么建议么?
You can use Array#map
along with Array#find
to obtain your expected result.您可以使用
Array#map
和Array#find
来获得预期的结果。
let Arr1 = [{ name: "raj", age: 20 }, { name: "ravi", age: 40 }]; let Arr2 = ['raj', 'ravi', 'arnold']; let result = Arr2.map(x=> Arr1.find(({name})=>name===x)??{name:x,age:null,available: 'no'} ); console.log(result);
I suggest a different approach and take an object for the given data and map the wanted names for eithe the given data or a new object.我建议采用不同的方法,并为给定的数据采用 object 并为给定的数据或新的 object 采用所需的名称 map。
This approach has a better big O, becaus it take a hash table and works fast for great data.这种方法有一个更好的大 O,因为它需要一个 hash 表并且可以快速处理大量数据。
const array1 = [{ name: "raj", age: 20 }, { name: "ravi", age: 40 }], array2 = ['raj', 'ravi', 'arnold'], data = array1.reduce((r, o) => (r[o.name] = o, r), {}), result = array2.map(name => data[name] || { name, age: null, available: 'no' }); console.log(result);
.as-console-wrapper { max-height: 100%;important: top; 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.