在javascript中按关系排序数组

时间:2015-06-23 12:51:37

标签: javascript arrays algorithm sorting object

我想对数组进行排序。

数组中的项目具有关系。

例如。 list[5]应为before list[9]after list[3]

样本中的预期值仅用于测试。它确实不存在。

这是一个包含关系和预期索引的示例数组。

var list = [{
  id: '0001',
  before: '0002',
  expected: 0
}, {
  id: '0002',
  before: '0007',
  after: '0001',
  expected: 4
}, {
  id: '0003',
  before: '0006',
  after: '0001',
  expected: 2
}, {
  id: '0004',
  after: '0007',
  expected: 11
}, {
  id: '0005',
  before: '0003',
  after: '0001',
  expected: 1
}, {
  id: '0006',
  before: '0002',
  after: '0001',
  expected: 3
}, {
  id: '0007',
  before: '00010',
  after: '0002',
  expected: 5
}, {
  id: '0008',
  before: '00012',
  after: '0007',
  expected: 9
}, {
  id: '0009',
  before: '0011',
  after: '0001',
  expected: 7
}, {
  id: '0010',
  before: '0009',
  after: '0007',
  expected: 6
}, {
  id: '0011',
  before: '0008',
  after: '0001',
  expected: 8
}, {
  id: '0012',
  before: '0004',
  after: '0010',
  expected: 10
}];

4 个答案:

答案 0 :(得分:3)

JanTengň扩展:这是一个例子,说明你的问题(在有向无环图中找到一个总订单)是如何无法解决的:

var list = [{ id:A, before:B }, // "First" in total order
            { id:B, after:A }, // "Last" in total order
            { id:C, after:A, before:B },
            { id:D, after:A, before:B }];

CD之间没有总排序:您可以将它们称为相等,但是如果不是D,您有一个列表D0 -> D1 -> D2会怎么样?

根据您的问题类型,这可以通过预处理来解决:将2级节点的路径减少到单个节点,并通过2级相同的节点调用并行路径(也可以简化为单个节点)。在这样的预处理结束时,你会留下一棵树 - 在你的情况下应该是一个列表/路径(或单个节点,因为你减少了2级顶点的路径)。

请注意,“之前”和“之后”的信息是多余的:您只需要其中一个。声明“A在B之前”等同于“B在A之后”并且您的非循环图只需要反映“之前”或“之后”的方向。您正在寻找的是包含所有节点的图形路径(因为它们是在“之前”或“之后”指示您自动从头到尾按顺序获取路径 - 如果存在这样的路径):

// First build the adjacency list for "X before Y"
var befores = { };
for(var i = 0; i < count; ++i)
    befores[list[i].id] = null;
function insert(before, after) {
    if(!before || !after)
        return;
    befores[before] = { next:befores[before], id:after };
}
for(var i = 0; i < count; ++i) {
    var item = list[i];
    insert(item.after, item.id); // "X after Y" -> "Y before X"
    insert(item.id, item.before);
}

// build complete the graph as a lookup table
// id is "before" all elements in lookup[id]
var lookup = { };
for(var i = 0; i < count; ++i) {
    var id = list[i].id;
    var beforeList = [id];
    var beforeSet = { };
    beforeSet[id] = 1;
    // use "A before B" and "B before C" to gain "A before C"
    for(var j = 0; j < beforeList.length; ++j) {
        for(var item = befores[beforeList[j]]; item != null; item = item.next) {
            if(!beforeSet[item.id]) {
                beforeList.push(item.id);
                beforeSet[item.id] = 1;
            }
        }
    }
    // for our comparison we don't care if id is in beforeSet
    lookup[id] = beforeSet;
    // slice beforeList to get only the elements after id here:
    //beforeList = beforeList.slice(1, beforeList.length);
}

// Now sort using the following
// a) if rhs is present in "before"-set of lhs then lhs < rhs
// b) if rhs is not present then rhs < lhs
// c) there is information missing from our graph if a) and b) for lhs analogous lead to a different conclusion!
list.sort(function(lhs, rhs) {
    if(!lhs.after || !rhs.before) return -1;
    if(!lhs.before || !rhs.after) return 1;
    if(lhs.id === rhs.id) return 0;
    // different ids guaranteed, doesn't matter if lookup[id] contains id itself
    var result = lookup[lhs.id][rhs.id] ? -1 : 1;
    // expect reversing lhs and rhs to get inverse result
    var expected = lookup[rhs.id][lhs.id] ? 1 : -1;
    if(result != expected) {
        // alert: there is no adjacency information between lhs and rhs!
    }
    return result;
});

自己测试一下:

var list = [{
  id: '0001',  before: '0002',  expected: 0}, {
  id: '0002',  before: '0007',  after: '0001',  expected: 4}, {
  id: '0003',  before: '0006',  after: '0001',  expected: 2}, {
  id: '0004',  after: '0007',  expected: 11}, {
  id: '0005',  before: '0003',  after: '0001',  expected: 1}, {
  id: '0006',  before: '0002',  after: '0001',  expected: 3}, {
  id: '0007',  before: '0010',  after: '0002',  expected: 5}, {
  id: '0008',  before: '0012',  after: '0007',  expected: 9}, {
  id: '0009',  before: '0011',  after: '0001',  expected: 7}, {
  id: '0010',  before: '0009',  after: '0007',  expected: 6}, {
  id: '0011',  before: '0008',  after: '0001',  expected: 8}, {
  id: '0012',  before: '0004',  after: '0010',  expected: 10
}];

// re-used variable
var count = list.length;
var out = document.getElementById("out");

function toHTMLItem(item) {
  var result = item.expected + " (";
  if(item.after) result += item.after + " &lt; ";
  result += "<b>" + item.id + "</b>";
  if(item.before) result += " &lt; " + item.before;
  result += ")";
  return result;
}

function toHTMLList(list) {
  var result = "<p>";
  for(var i = 0; i < count; ++i) {
    result += toHTMLItem(list[i]) + "<br>";
  }
  result += "</p>";
  return result;
}

// out.innerHTML += toHTMLList(list);

var befores = { };
for(var i = 0; i < count; ++i)
	befores[list[i].id] = null;
function insert(before, after) {
	if(!before || !after)
		return;
	befores[before] = { next:befores[before], id:after };
}
for(var i = 0; i < count; ++i) {
	var item = list[i];
	insert(item.after, item.id);
	insert(item.id, item.before);
}

function toHTMLTable(table, list) {
  var result = "<p>";
  var count = list.length;
  for(var i = 0; i < count; ++i) {
    var id = list[i].id;
    result += id + " < ";
    for(var item = table[id]; item != null; item = item.next) {
      result += item.id + ", ";
    }
    result += "o<br>";
  }
  result += "</p>";
  return result;
}

// out.innerHTML += toHTMLTable(befores, list);

// next build a lookup-table of a completed adjacency list
var lookup = { };
for(var i = 0; i < count; ++i) {
	var id = list[i].id;
	var beforeList = [id];
	var beforeSet = { };
	beforeSet[id] = 1;
	// use "A before B" and "B before C" to gain "A before C"
	for(var j = 0; j < beforeList.length; ++j) {
		for(var item = befores[beforeList[j]]; item != null; item = item.next) {
			if(!beforeSet[item.id]) {
				beforeList.push(item.id);
				beforeSet[item.id] = 1;
			}
		}
	}
	beforeList = beforeList.slice(1, beforeList.length);
	beforeList.sort();
	lookup[id] = beforeSet;
}

function toHTMLLookup(lookup, list) {
  var result = "<p>";
  for(var i = 0, imax = list.length; i < imax; ++i) {
    var id = list[i].id;
    var bs = lookup[id];
    result += id + " < ";
    for(var j = 0, jmax = imax; j < jmax; ++j) {
      if(j == i) continue;
      if(bs[list[j].id]) result += list[j].id + ", ";
    }
    result += "o<br>";
  }
  result += "</p>";
  return result;
}

// out.innerHTML += toHTMLLookup(lookup, list);

// Search function in befores:
// a) if rhs is present in union of befores set lhs < rhs
// b) if rhs is not present in union of befores set rhs < lhs
list.sort((function() {
  var enableAlert = true;
  return function(lhs, rhs) {
    if(!lhs.after || !rhs.before) return -1;
    if(!lhs.before || !rhs.after) return 1;
    if(lhs.id === rhs.id) return 0;
    // different ids guaranteed, doesn't matter if lookup[id] contains id itself
    var result = lookup[lhs.id][rhs.id] ? -1 : 1;
    // expect reversing lhs and rhs to get inverse result
    var expected = lookup[rhs.id][lhs.id] ? 1 : -1;
    if(enableAlert && result != expected) {
      // restrict to a single alert per execution
      enableAlert = false;
      out.innerHTML += "<p><b>ALERT</b> unresolved adjacency between " + lhs.id + " and " + rhs.id + "!</p>";
    }
    return result;
  };
})());

// out.innerHTML += toHTMLList(list);

var error = count;
for(var i = 0; i < error; ++i) {
	if(list[i].expected != i)
		error = i;
}
if(error < count) {
  out.innerHTML += "<h2>error!</h2><p>list[" + error + "] contains " + toHTMLItem(list[i]) + "</p>";
} else {
  out.innerHTML += "<h2>success!</h2>";
}
// Finally print the output
out.innerHTML += toHTMLList(list);
<div id="out"/>

对于这个问题的一般主题,请考虑topological sorting

答案 1 :(得分:1)

部分答案,评论太久了。您可能已经想到了这一点,我希望它可以帮助某人找到解决方案。

  1. 解决方案可能是不可能的,也可能是其中之一
  2. 如果&#34;之前有&#34;或&#34;之后&#34;遍历,没有解决方案(@ BeyelerStudios&#39;信用)
  3. 第一个没有&#34;在&#34;之后,最后一个没有&#34;&#34;
  4. 第二个必须在&#34;中有第一个id;在&#34;之后,可以设置
  5. 该集合可以递归排序
  6. 如何确定我无法弄清楚的剩余元素的位置。
  7. 此功能在就地排序中非常有用:在数组中移动项目:

    Object.defineProperty(Array.prototype,"move",{
      value: function(from,to) {
        var x = this.splice(from,1);
        this.splice(to,0,x[0]);
      }
    });
    
    var list = ['a','b','c','d','e'];
    // move the index 1 (b) to position 3 (after d)
    list.move(1,3); // acdbe
    
    祝你好运。

答案 2 :(得分:0)

如果我理解这一点,expected是你喜欢该元素的索引吗?在这种情况下,您可以将.sort()与自定义排序功能结合使用。

list.sort(function (a, b) {
  var ae = a.expected,
      be = b.expected;

  if (ae > be) return 1;
  if (ae < be) return -1;
  if (ae === be) return 0;
});

(如果您因牺牲可读性而牺牲时,可以缩短该块。)

答案 3 :(得分:0)

你想要的是一个自定义排序功能,正如Mike所说。我想你真正想要的是:

list.sort(function(a, b) {
  if (/* a before b, b after a */) {
    return -1;
  } else if (/* b before a, a after b */) {
    return 1;
  } 
  return 0;
});

基本上,您在自定义排序函数中返回的内容决定了两个参数之间的关系。返回-1表示第一个项目在之前,+1表示第二个项目在之前,0表示没有可用的关系。

对于您的“a b之后,b之前的b”标准,也许可以尝试a.id === b.before|| b.id === a.after,而a后面的反向为。

根据您的确切列表,这可能会或可能不会按预期返回 - 如果您有大量丢失或冲突的数据,排序可能最终无法完全按预期返回。

一般来说,我会避免同时拥有“之前”和“之后”信息 - 你应该只需要一个或另一个,并且两者都可以引入更多的冲突,而不仅仅是单一的关系。