代码之家  ›  专栏  ›  技术社区  ›  Jessica

基于对象数组对字符串数组排序

  •  0
  • Jessica  · 技术社区  · 5 年前

    我正在尝试基于对象数组对字符串数组进行排序(数组的项目数将与对象的项目数不同。)

    const myObject = [
        {
            title: 'Some string'
        },
        {
            title: 'another string'
        },
        {
            title: 'Cool one'
        }
    ];
    
    const array = ['Cool one', 'Some string']; // Sort this array based on 'myObject'
    
    3 回复  |  直到 5 年前
        1
  •  3
  •   Patrick Roberts Benjamin Gruenbaum    5 年前

    您可以生成一个索引表,根据该表对数据进行排序 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);
        2
  •  2
  •   brk    5 年前

    您可以使用reduce&查找索引。在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)
        3
  •  0
  •   user1971419 user1971419    5 年前

    我想你可以用 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)