首页 > 解决方案 > 使用另一个数组对对象数组进行排序

问题描述

我有一个像这样的对象数组,想用另一个对象数组重新排序。我曾尝试使用 indexOf 但可能会混淆我的语法,因为数组无法重新排序。我已经阅读了类似的问题,但无法将这些解决方案应用于我的问题。这是代码:

    const task = [
       {'title':1.1 , 'description': 'task description here' },
       {'title':1.2 , 'description': 'task description here' },
       {'title':1.3 , 'description': 'task description here' },
       {'title':1.4 , 'description': 'task description here' }
    ];

    var taskSort = [
            {'title':1.2 },
            {'title':1.4 },
            {'title':1.3 },
            {'title':1.1 }
        ];

    task.sort(function(a, b) {
      return taskSort.indexOf(a.title) - taskSort.indexOf(b.title); \\have tried many variations of this line
    });
    console.clear();
    console.log(task);

提前谢谢了!

标签: javascriptarrayssortingobject

解决方案


基本上,您不是对值进行排序,而是根据另一个数组中指定的顺序重新排列它们

因此,您不能使用该Array.prototype.sort逻辑,但可以执行以下操作

var taskSort = [
            {'title':1.2 },
            {'title':1.4 },
            {'title':1.3 },
            {'title':1.1 }
        ];
   var task = [
       {'title':1.1 , 'description': 'task description here' },
       {'title':1.2 , 'description': 'task description here' },
       {'title':1.3 , 'description': 'task description here' },
       {'title':1.4 , 'description': 'task description here' }
    ];
   var sortedTask = taskSort.map(tS => task.find(t => t.title === tS.title))

console.log(sortedTask);

本质上,您正在映射 taskSort 数组并创建一个新数组,其中的值满足 taskSort 数组中的值标记的条件


推荐阅读