猿问

通过 JavaScript 中给定的不完整订单数组对对象数组进行排序

我有一个对象数组:


var items = [

   {

      "id":"sugar",

      "type": 'eatables'

   },

   {

      "id":"petrol",

      "type": 'utility'

   },

   {

      "id":"apple",

      "type": 'fruits'

   },

   {

      "id":"mango",

      "type": 'fruits'

   },

   {

      "id":"book",

      "type": 'education'

   }

];

现在我有另一个订单数组,我想借助它对items数组进行排序:


var orders = [

   {

      "id":"sugar",

      "order":5

   },

   {

      "id":"book",

      "order":1

   }

];

现在,到目前为止,我在逻辑上所尝试的是,我放置了太多循环,以至于完全造成了混乱。


谁能建议我为此提供一个简短且优化的逻辑?


守候你守候我
浏览 110回答 2
2回答

ITMISS

一种方法可能是创建一个字典,该字典将保留order每个元素的 。另外,我还迭代了整个items数组来存储不在数组中的元素的位置orders。首先,我将声明一个保留整个订单的数组,即一个包含元素的数组。1..Nvar orderNumbers = Array.from({length: items.length}, (_, v) => v + 1);然后我开始通过迭代数组来创建字典orders并从中删除订单orderNumbers。最后一步是迭代items数组并使用shift方法到"pop"第一个元素。最终的字典看起来像{&nbsp; "sugar": 2,&nbsp; "book": 3,&nbsp; "petrol": 1,&nbsp; "apple": 4,&nbsp; "mango": 5}在此代码中,我使用了一本字典,因为它的复杂性lookup为.O(1)var items = [ { "id":"sugar", "type": 'eatables' }, { "id":"petrol", "type": 'utility' }, { "id":"apple", "type": 'fruits' }, { "id":"mango", "type": 'fruits' }, { "id":"book", "type": 'education' } ], orders = [ { "id":"sugar", "order":2 }, { "id":"book", "order":3 } ], orderNumbers = Array.from({length: items.length}, (_, v) => v + 1);var ordersDict = orders.reduce((acc, item) => {&nbsp;&nbsp; &nbsp; &nbsp;acc[item.id] = item.order;&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp;//remove from order numbers&nbsp; &nbsp; &nbsp;let index = orderNumbers.findIndex(el => el == item.order);&nbsp; &nbsp; &nbsp;orderNumbers.splice(index, 1);&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp;return acc;}, {});for(let i = 0; i < items.length; i++){&nbsp; if(!ordersDict.hasOwnProperty(items[i].id)){&nbsp; &nbsp; ordersDict[items[i].id] = orderNumbers[0];&nbsp; &nbsp; orderNumbers.shift();&nbsp; &nbsp;}}//sort the arrayitems.sort((a,b) => ordersDict[a.id] - ordersDict[b.id]);console.log(items);

繁花如伊

let oorder = new Object();orders.map(item=>{oorder[item.id]=item.order});var new_items = [];items.map(item=>{new_items[oorder[item.id]-1]=item});
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答