簡體   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