I have Two Array with nested objects
let arrOne = [{ id:01, name:'haris' },{ id:02, name:'papi' },{ id:03, name:'john' }];
let arrTwo = [{ jobId:03, name:'haha' },{ jobId:01, name:'kaka' }];
Now I want to filter out the arrOne in such a way that arrOne id is matched with arrTwo jobId Like this:
arrOne.filter((ele,index) => ele.id == (arrTwo)[index]?.jobId)
But it returns [ ] empty array, although if I will rearrange arrTwo in such way like:
let arrTwo = [{ jobId:01, name:'haha' },{ jobId:02, name:'kaka' }];
it will return the matched value.
so what's the problem here & How to resolve this?
Thank you
CodePudding user response:
A simple solution using find()
inside filter()
to get the result
And for your question,it's because you are using index
,however the value with same index
are not the same in these two array. And if you change the element order in arrTwo
,then the same index will get some data for you
let arrOne = [{ id:01, name:'haris' },{ id:02, name:'papi' },{ id:03, name:'john' }];
let arrTwo = [{ jobId:03, name:'haha' },{ jobId:01, name:'kaka' }];
let result = arrOne.filter(a1 => arrTwo.find(a2 => a2.jobId == a1.id));
// or with some()
//let result = arrOne.filter(a1 => arrTwo.some(a2 => a2.jobId == a1.id));
console.log(result);