如何根据对象之间的映射键对 Javascript 对象数组进行排序

问题描述 投票:0回答:1

我需要编写一个函数,根据dialog_node 键和previous_sibling 键对该数组进行排序。下一个对象的 previous_sibling 与数组中前一个对象的dialog_node 值匹配。


export function orderDialogNodes(nodes) {
  // Create a mapping of dialog_node to its corresponding index in the array
  const nodeIndexMap = {};

  nodes.forEach((node, index) => {
    nodeIndexMap[node.dialog_node] = index;
  });

  // Sort the array based on the previous_sibling property
  nodes.sort((a, b) => {
    const indexA = nodeIndexMap[a.previous_sibling];
    const indexB = nodeIndexMap[b.previous_sibling];

    return indexA - indexB;
  });

  return nodes;
}

const inputArray = [
 {
    type: "folder",
    dialog_node: "node_3_1702794877277",
    previous_sibling: "node_2_1702794723026",
  }, {
    type: "folder",
    dialog_node: "node_2_1702794723026",
    previous_sibling: "node_9_1702956631016",
  },
  {
    type: "folder",
    dialog_node: "node_9_1702956631016",
    previous_sibling: "node_7_1702794902054",
  },
];

const orderedArray = orderDialogNodes(inputArray);
console.log(orderedArray);
javascript arrays sorting
1个回答
0
投票

这可能有用

function orderDialogNodes(nodes) {
  return [...nodes].sort((a, b) => {
    if (a.previous_sibling === b.dialog_node) {
      return 1
    }
    if (b.previous_sibling === a.dialog_node) {
      return -1
    }
    return 0
  });
}

const inputArray = [
 {
    type: "folder",
    dialog_node: "node_3_1702794877277",
    previous_sibling: "node_2_1702794723026",
  }, {
    type: "folder",
    dialog_node: "node_2_1702794723026",
    previous_sibling: "node_9_1702956631016",
  },
  {
    type: "folder",
    dialog_node: "node_9_1702956631016",
    previous_sibling: "node_7_1702794902054",
  },
];

const orderedArray = orderDialogNodes(inputArray);
console.log(orderedArray);

© www.soinside.com 2019 - 2024. All rights reserved.