前端两个数组怎么匹配?

现在知道一个数组a和b,想根据a数组的值为id把b对应的数据都拿出来弄个新数组如下,改怎么操作简便点

[

{id:"110",name:"警察"},

{id:"150",name:"医生"},

{id:"190",name:"警察"}

]

var a = [110,150,190];

var b = [

{id:"110",name:"警察"},

{id:"120",name:"医生"},

{id:"130",name:"警察"},

{id:"140",name:"警察"},

{id:"150",name:"医生"},

{id:"160",name:"警察"},

{id:"170",name:"警察"},

{id:"180",name:"医生"},

{id:"190",name:"警察"},

];


回答:

// 数据量不大,直接双重循环查找即可(复杂度O(n*m))

b.filter(v => a.some(id => v.id == id))

// 数据量较大时,将id转为set/map/object以提升查询速度(复杂度O(n),空间复杂度O(m))

var ids = new Set(a);

b.filter(v => ids.has(+v.id)) // 因为set里string/number是不同值,需要统一类型


回答:

for 循环不会吗?

var a = [110,150,190];

var b = [

{id:"110",name:"警察"},

{id:"120",name:"医生"},

{id:"130",name:"警察"},

{id:"140",name:"警察"},

{id:"150",name:"医生"},

{id:"160",name:"警察"},

{id:"170",name:"警察"},

{id:"180",name:"医生"},

{id:"190",name:"警察"},

];

let result = [];

for(let i = 0; i < b.length; i++) {

const id = b[i].id;

if(a.findIndex(i => i === Number(id)) > -1) {

result.push(b[i]);

}

}

// 再简洁一点,用 filter 方法

const result = b.filter(item => a.findIndex(i => i === Number(item.id)) > -1);

filterfindIndex 都是数组的方法,可以搜索看一下具体用法。


回答:

简单点就是

let result = a.map(id => b.find(r => r.id == id))

减少循环次数

let bMap = {}

b.forEach(item => {

bMap[item.id] = item

})

let result = a.map(id => bMap[id])

或者更少

let bMap = {}

let result = a.map(id => {

if (bMap[id] !== undefined) {

return bMap[id]

}

return b.find(r => {

if (bMap[r.id] === undefined) {

bMap[r.id] = r

}

return r.id === id

})

})

以上是 前端两个数组怎么匹配? 的全部内容, 来源链接: utcz.com/p/933346.html

回到顶部