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

标签 javascript arrays sorting

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

代码如下:

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/

相关文章:

浏览器调整大小的 JavaScript

javascript - 在 IE5 中将项目添加到 <select>

javascript - 在 React 中将一个数组中的值分配给另一个数组

Java 对并行数组进行排序,需要帮助(NullPointerException 错误)

php - 循环数组,不返回期望的结果

python - 在 numpy 数组中组合逻辑语句 AND

perl - 文件中最常用的字符串

排序行组Excel VBA宏

javascript - 如何删除人力车直方图中的垂直线?

sorting - 定义一个过程,该过程将三个数字作为参数并返回两个较大数字的平方和