用另一个数组对对象数组进行排序

时间:2019-12-04 14:33:09

标签: javascript arrays sorting object

我有一个这样的对象数组,并想与另一个对象数组重新排序。我尝试使用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);

非常感谢!

4 个答案:

答案 0 :(得分:1)

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

因此,您不能使用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数组中的值所标记的条件

答案 1 :(得分:1)

您可以使用所需的title顺序构建对象,并取值的差值进行排序。

采用这种方法,如果不知道title的值,则可以默认添加值。然后,您可以将这些项目移至Number.MAX_VALUE的底部或移至-Number.MAX_VALUE的顶部,例如

(order[a] || -Number.MAX_VALUE) - (order[b] || -Number.MAX_VALUE) //   top 
(order[a] || Number.MAX_VALUE) - (order[b] || Number.MAX_VALUE)  // bottom

 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' }];
    taskSort = [ { title: 1.2 }, { title: 1.4 }, { title: 1.3 }, { title: 1.1 }],
    order = Object.fromEntries(taskSort.map(({ title }, i) => [title, i + 1]));

task.sort(({ title: a }, { title: b }) => order[a] - order[b]);

console.log(task);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:0)

您没有得到预期的结果,因为您正在检查对象数组(taskSort)中的int(a.title)索引。因此,由于没有这样的元素,taskSort.indexOf(a.title)总是返回-1。最简单的方法是像这样修改任务排序:

var taskSort = [1.2, 1.4, 1.3, 1.1];

一切都会按预期进行。

答案 3 :(得分:0)

您的实现实际上非常接近,我认为您只需要使用findIndex而不是诸如indexOf即可:

return taskSort.findIndex(element => element.title === a.title) - taskSort.findIndex(element => element.title === b.title);

indexOf尝试将输入与数组的确切元素而不是元素的属性进行匹配。

相关问题