首页 > 解决方案 > Javascript基于另一个数组对对象数组进行排序

问题描述

我有一个对象数组,我需要根据另一个数组对象进行排序。这是需要排序的给定数组:

const arr1 = [
    {
      id: 21,
      name: 'Joey',
      vehicle: 'car'
    },
    {
      id: 6,
      name: 'Kevin'
      vehicle: 'car'
    },
    {
      id: 10,
      name: 'Luis'
      vehicle: 'van'
    }
  ]

这是按正确顺序排列的数组:

 const arr2 = [
    {
      id: 6,
      name: 'Kevin'
    },
    {
      id: 21,
      name: 'Joey'
    },
    {
      id: 10,
      name: 'Luis'
    }
  ]

arr2它只是从我的数据库返回的数据没有特定的顺序。我基本上只需要按照与 arr2 中相同的顺序将 id 放入 arr1 中。我试过使用 findIndex 和排序,但我很困惑

标签: javascript

解决方案


那 ?

const arr1 = 
      [ { id: 21, name: 'Joey',  vehicle: 'car' } 
      , { id: 6,  name: 'Kevin', vehicle: 'car' } 
      , { id: 10, name: 'Luis',  vehicle: 'van' } 
      ] 

const arr2 = 
      [ { id: 6,  name: 'Kevin' } 
      , { id: 21, name: 'Joey'  } 
      , { id: 10, name: 'Luis'  } 
      ] 

      
// Arr1 ordered..
const arr1_ord = arr2.map(a2=> arr1.find(x=>x.id===a2.id))

console.log( arr1_ord )
.as-console-wrapper {max-height: 100%!important;top:0}

此外,如果 arr2 中只有 2 个项目,我仍然希望那些缺失的元素位于排序后的 arr1 末尾。这能解决吗?

我添加了另一种情况:arr2 元素没有 arr1 相同的 id

const arr1 = 
  [ { id: 21, name: 'Joey',  vehicle: 'car'       } 
  , { id: 6,  name: 'Kevin', vehicle: 'car'       } 
  , { id: 12, name: 'George', vehicle: 'carriage' } // not in arr2
  , { id: 10, name: 'Luis',  vehicle: 'van'       } 
  ] 

const arr2 = 
  [ { id: 6,  name: 'Kevin' } 
  , { id: 21, name: 'Joey'  } 
  , { id: 88, name: 'none'  } // not in arr1  
  , { id: 10, name: 'Luis'  } 
  ] 

      
// Arr1 ordered..
const arr1_ord = arr2.reduce((res, {id},i,{[i+1]:next})=>
  {
  let a1 = arr1.find(x=>x.id===id)
  if (a1) res.push(a1)  // if exist in arr1
  if (next) return res
  else return [...res, arr1.filter(r=>!res.some(z=>z.id===r.id))] // add the missing elements
  },[])

console.log(  arr1_ord )
.as-console-wrapper {max-height: 100%!important;top:0}


推荐阅读