如何避免将重复项推送到数组中

时间:2018-03-30 17:06:31

标签: javascript json

我如何确保当我推动一个新节点时,如果它已经存在,那么就不会推动它,否则推它。

function defineGraph(edges){
  // Define the graph
  var graph = { nodes: Object.create(null) };

  // Define nodes and edges
  graph.nodes = []
  graph.edges = []

  // Add content to graph.nodes and graph.edges
  edges.forEach(function (edge) {
    var [f, labels, t, att] = edge;
    graph.nodes.push({label: f, attributes: att})
    graph.nodes.push({label: t, attributes: []})

    graph.edges.push([f, t, [labels]])
  });

  return graph; }

如果,它应该是任何帮助我的输出格式是JSON。例如,

"nodes": [
  {
     "label": "a",
     "attributes": [
        "initial"
     ]
  }, {...}

2 个答案:

答案 0 :(得分:0)

也许是这样的:

是否可以将节点和边缘定义为对象而不是数组?如果是这样,您可以检查对象的属性:

graph.nodes = {};

// Assuming you index your nodes by, ie, attr
if (typeof graph.nodes.attr === 'undefined') {
    graph.nodes.push({label: f, attributes: att})
    graph.nodes.push({label: t, attributes: []})
}

如果节点需要是一个数组,那么你应该检查索引的索引。这种解决方案更昂贵:

graph.nodes = [];

if (graph.nodes.indexOf(attr) === -1) {
    graph.nodes.push({label: f, attributes: att})
    graph.nodes.push({label: t, attributes: []}
}

答案 1 :(得分:0)

您可以在推入阵列之前深入检查对象。你可以使用lodash库。

const isEqual = _.isEqual({a: 'b', y:'z'}, {a: 'b', y:'z'})
// here isEqual will be true.

您可以在代码中应用此功能,如下所示

edges.forEach(edge => {
  const [f, labels, t, att] = edge;

  const node1 = {label: f, attribute: att};
  if (!graph.nodes.find(n => _.isEqual(n, node1) {
    graph.nodes.push(node1);
  }

  const node2 = {label: t, attributes: []};
  if (!graph.nodes.find(n => _.isEqual(n, node2) {
    graph.nodes.push(node2);
  }

  const edge1 = [f, t, [labels]];
  if (graph.edges.find(e => _.isEqual(e, edge1) {
    graph.edges.push(edge1);
  }
});