我正在尝试根据对象数组对字符串数组进行排序。 (数组中的项目数量与对象的数量不同。)
代码如下:
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/