undefinedfix
Sign in

JS according to the key value, brush out the items that meet the conditions to form a new array

Pierric edited in Wed, 18 May 2022

Title Description

There is an array, such as let arr = ["banana", "apple", "pear];, and then another object array:

let arr = ["香蕉","苹果","梨"];


// 对象数组
let allArr = [
    {id:'001',name:'苹果',price:'2'},
    {id:'002',name:'香蕉',price:'1'},
    {id:'003',name:'梨',price:'20'},
    {id:'004',name:'西瓜',price:'22'},
    {id:'005',name:'草莓',price:'26'}
];


// 最终结果:新数组,根据arr的值,筛选出符合条件的对象,组成新的数组;
// 要求顺序一致
let finalArr = [
    {id:'002',name:'香蕉',price:'1'},
    {id:'001',name:'苹果',price:'2'},
    {id:'003',name:'梨',price:'20'}
];
3 Replies
Kawazack
commented on Wed, 18 May 2022
   arr.forEach((a) => {
       allArr.forEach((all) => {
          if(a === all.name){
             finalArr.push(all);
          }
       })
    })
kqico
commented on Wed, 18 May 2022
const finalArr = allArr
  .filter(a => arr.includes(a.name))
  .sort((a, b) => arr.indexOf(a.name) - arr.indexOf(b.name))
obidano
commented on Wed, 18 May 2022

allArr.filter (i => arr.some (_ i => i.name === _ i)).sort((a, b) => arr.indexOf (a.name) - arr.indexOf (b.name) >= 0 ? 1 : -1)

lock This question has been locked and the reply function has been disabled.