1

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

1
  • 1
    The filtering works. Now the order is a different problem altogether. After your filtering is done, you have to perform additional logic so the filtered array is in the same order as arr2. Or you can do const arr3 = arr2.map( name => arr1.find( obj => obj.id===name )) Commented Feb 22, 2022 at 14:00

2 Answers 2

1

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);

Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.