繁体   English   中英

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

[英]Sort an array of objects with another array

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

提前谢谢了!

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

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

您可以使用所需的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; }

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

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

一切都应该按预期工作。

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM