按特定顺序重新排序对象数组

时间:2018-02-15 13:36:53

标签: javascript arrays sorting

我有两个数组,一个是import numpy as np import matplotlib.pyplot as plt #turn interactive mode on plt.ion() def GetTestData(): data = [] for i in range(0, 2048): data.append(np.random.random_sample() * i) return data fig = plt.figure() ax1 = fig.add_subplot(111) ax2 = ax1.twiny() line1, = ax1.plot(GetTestData()) line2, = ax2.plot(range(100), np.ones(100)) for i in range(0, 100): line1.set_ydata(GetTestData()) #line2.set_ydata(range(100), np.ones(100)) plt.pause(0.05) fig.canvas.draw() ,基本上是和数组,另一个是contentOrder,它是和对象数组,我希望使用id的顺序对第二个数组进行排序从第一个数组怎么可以做到这一点。

contentOrder

blocksContent

blocksContent

contentOrder = [
    "de19b7c5-ff69-4fce-a38d-c6f0ee0d1eb5",
    "58f0dcfe-55d8-447d-87cc-fc00ec068407",
    "58f0dcfe-55d8-447d-87cc-fc00ec085407"
    ]

2 个答案:

答案 0 :(得分:1)

使用sortindexOf功能。



var contentOrder = [
    "de19b7c5-ff69-4fce-a38d-c6f0ee0d1eb5",
    "58f0dcfe-55d8-447d-87cc-fc00ec068407",
    "58f0dcfe-55d8-447d-87cc-fc00ec085407"
    ]


var blocksContent= [
  {blockId: "58f0dcfe-55d8-447d-87cc-fc00ec068407", documentId: 298, chapterId: "4c26640a-bcda-4788-aee3-5c1508f70a67"},
  {blockId: "58f0dcfe-55d8-447d-87cc-fc00ec085407", documentId: 298, chapterId: "4c26640a-bcda-4788-aee3-5c1508f70a67"},
  {blockId: "de19b7c5-ff69-4fce-a38d-c6f0ee0d1eb5", documentId: 298, chapterId: "4c26640a-bcda-4788"}
]

blocksContent.sort((a, b) => contentOrder.indexOf(a.blockId) - contentOrder.indexOf(b.blockId));

console.log(blocksContent);

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




答案 1 :(得分:0)

let sortedContent = []

contentOrder.forEach((val) => {
  blocksContent.forEach((val1)=> {
    if(val == val1.blockId)
      sortedContent.push(val1)
  })
})