javascript - 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 和排序,但我很困惑
解决方案
那 ?
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}
推荐阅读
- python - 从 python 文件加载函数时遇到问题
- javascript - 如何强制用户按顺序点击 div?
- segmentation-fault - google-assistant-demo 和 googlesamples-assistant-hotword 分段错误
- wordpress - Wordpress 如何使过滤器在 Wordpress API 中返回 author_name
- php - 作曲家更新最后说 Trait 'Carbon\Traits\Mixin' not found
- docker - 在 Dockerfile 基础映像中公开端口是否会在最终映像中公开它们?
- python - [[]]*X 不创建唯一数组
- postgresql - \COPY TO Postgres 语句在 bash 中工作,但不适用于 python psycopg2
- python - Python - 根据其他变量自动创建新变量
- c - 将内存分配给结构中的数组