gpt4 book ai didi

javascript - 根据对象数组对字符串数组进行排序

转载 作者:行者123 更新时间:2023-11-30 08:18:12 25 4
gpt4 key购买 nike

我正在尝试根据对象数组对字符串数组进行排序。 (数组中的项目数量与对象的数量不同。)

代码如下:

const myObject = [
{
title: 'Some string'
},
{
title: 'another string'
},
{
title: 'Cool one'
}
];

const array = ['Cool one', 'Some string']; // Sort this array based on 'myObject'

最佳答案

您可以生成一个索引表,通过它对您的 array 进行排序,如下所示:

const myObject = [
{ title: 'Some string' },
{ title: 'another string' },
{ title: 'Cool one' }
];
const indices = Object.fromEntries(
myObject.map(
({ title }, index) => [title, index]
)
);
const array = ['Cool one', 'Some string'];

array.sort((a, b) => indices[a] - indices[b]);

console.log(array);

关于javascript - 根据对象数组对字符串数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58315271/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com