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

时间:2019-10-10 03:59:42

标签: 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'

3 个答案:

答案 0 :(得分:3)

您可以生成一个索引表,通过它可以对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);

答案 1 :(得分:2)

您可以使用reduce&findIndex。在reduce回调函数内部,使用findIndex检查元素是否存在于myObject中。如果是这样,则获取索引并使用该索引将值添加到累加器数组中

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

const array = ['Cool one', 'Some string'];

let newArray = array.reduce(function(acc, curr) {
  let findIndex = myObject.findIndex(a => a.title.toLowerCase().trim() == curr.toLowerCase().trim());
  if (findIndex !== -1) {
    acc.push(myObject[findIndex])
  }
  return acc;
}, []);

console.log(newArray)

答案 2 :(得分:0)

我认为您可以与Array.findIndex()一起使用Array.sort()帮助您解决这个问题

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

const stringArray = [
  'Cool one',
  'Some string'
]

const sortFromObject = (a, b) => {

  // get the indexes of the objects
  const idxA = objectArray
     .findIndex(obj => obj.title === a)
  const idxB = objectArray
     .findIndex(obj => obj.title === b)

  // if it comes first in the object array,
  // sort this item up, else sort it down
  return idxA - idxB
}

stringArray.sort(sortFromObject)