简体   繁体   English

如何从具有特定 id 的数组中获取对象与另一个数组编号进行比较

[英]How can I get objects from array with specific id compares from another array numbers

I need to compare id objects array from a firstArray and array numbers (secondArray) and return a new array with objects from the first array which id number exists in the second array.我需要比较来自 firstArray 和数组编号 (secondArray) 的 id 对象数组,并返回一个包含来自第一个数组的对象的新数组,该数组的 id 编号存在于第二个数组中。

So at the end, I want a new array with objects with id 39 and 41.所以最后,我想要一个包含 id 为 39 和 41 的对象的新数组。

Actually I find something like this:其实我发现是这样的:

const result = arr2.filter(o => arr1.find(x => x.id === o));

const arr1 =
"blocks": [
    {
      "id": 1,
      "functions": [ 0, 1 ]
    },
    {
      "id": 39,
      "functions": [ 0, 1, 3, 4 ]
    },
    {
      "id": 41,
      "functions": [ 0, 1 ]
    }
]

const arr2 = [39, 41]

You can create a Map to see whether there is an item of Map exists in filtering array.您可以创建一个Map来查看过滤数组中是否存在 Map 项。 Getting an item from Map method is O(1) :Map方法获取一个项目是O(1)

 const blocks = [ { "id": 1, "functions": [ 0, 1 ] }, { "id": 39, "functions": [ 0, 1, 3, 4 ] }, { "id": 41, "functions": [ 0, 1 ] } ]; const arr2 = [39, 41]; const arr2Maps = new Map(arr2.map(a=>[a, a])); const result = blocks.filter(o => arr2Maps.get(o.id)); console.log(result)

In addition, you can use filter and some methods.此外,您可以使用filtersome方法。 However, some method has O(n) :但是, some方法具有O(n)

 const blocks = [ { "id": 1, "functions": [ 0, 1 ] }, { "id": 39, "functions": [ 0, 1, 3, 4 ] }, { "id": 41, "functions": [ 0, 1 ] } ]; const arr2 = [39, 41] const result = blocks.filter(o => arr2.some(a=> a ==o.id )); console.log(result)

You can use includes() function during filtering.您可以在过滤过程中使用includes()函数。 Includes() works like in array function. Includes()工作方式类似于in array函数。

 const arr1 = [ { "id": 1, "functions": [ 0, 1 ] }, { "id": 39, "functions": [ 0, 1, 3, 4 ] }, { "id": 41, "functions": [ 0, 1 ] } ] const arr2 = [39, 41] const result = arr1.filter(o => arr2.includes(o.id)); console.log(result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM