Javascript - sort array based on another array

后端 未结 22 1430
鱼传尺愫
鱼传尺愫 2020-11-22 03:45

Is it possible to sort and rearrange an array that looks like this:

itemsArray = [ 
    [\'Anne\', \'a\'],
    [\'Bob\', \'b\'],
    [\'Henry\', \'b\'],
             


        
22条回答
  •  清酒与你
    2020-11-22 04:18

    function sortFunc(a, b) {
      var sortingArr = ["A", "B", "C"];
      return sortingArr.indexOf(a.type) - sortingArr.indexOf(b.type);
    }
    
    const itemsArray = [
      {
        type: "A",
      },
      {
        type: "C",
      },
      {
        type: "B",
      },
    ];
    console.log(itemsArray);
    itemsArray.sort(sortFunc);
    console.log(itemsArray);

提交回复
热议问题