Home > Mobile >  how do I match the data and return same data of first array
how do I match the data and return same data of first array

Time:02-23

I have two array

arr1 =[{name:'Net Banking', id:'NetBanking'},{name:'Debit Card', id:'DebitCard'},{name:'Credit Card', id:'CreditCard'}]

and

arr2=['DebitCard','NetBanking']

and I want to expected result as of arr1

arr1=[{name:'Debit Card', id:'DebitCard'}, {name:'Net Banking', id:'NetBanking'}]

currently I am using -

arr1.filter(data=>arr2.includes(data.id))

and I am getting return as

arr1 =[{name:'Net Banking', id:'NetBanking'},{name:'Debit Card', id:'DebitCard'}]

means match the element of arr2 with arr1 and return as arr1 with same order of arr2

or how can I change the index based on arr2 of arr1

CodePudding user response:

You can use Array.map() along with Array.find() to get the desired input.

Working Demo :

const arr1 =[{name:'Net Banking', id:'NetBanking'},{name:'Debit Card', id:'DebitCard'},{name:'Credit Card', id:'CreditCard'}];

const arr2=['DebitCard','NetBanking'];

const resArray = arr2.map((item) => arr1.find((obj) => obj.id === item));

console.log(resArray);

CodePudding user response:

You can loop through arr2 and for each item find the related object with the same id in array arr1

You can rely on

  1. Array.prototype.find
  2. Array.prototype.reduce

let arr1 =[{name:'Net Banking', id:'NetBanking'},{name:'Debit Card', id:'DebitCard'},{name:'Credit Card', id:'CreditCard'}];

let arr2=['DebitCard','NetBanking'];

const result = arr2.reduce((accumulator, current) => {
   /*
   * For the current item of the loop search for item with
   * object.id === current
   */
   return accumulator.concat(arr1.find(item => item.id === current));
},[]);

console.log(result);

  • Related