您好我有一个很长的JSON键键值对的列表:值,键:值等
Hi I have a very long list of key value pairs in json key:value, key:value and so on
car <--> wheel
wheel <--> tyre
bed <--> sheets
guitar <--> strings
guitar <--> pickup
tyre <--> rubber
我要的是把所有的关系到阵列无论多么遥远像这样
What I want is to group all relations into arrays no matter how distant like this
[car, wheel, tyre, rubber]
[guitar, strings, pickup]
[bed, sheets]
什么是有效的方式使用Javascript做到这一点?
What is an efficient way to do this with Javascript?
首先,我将存储的关系作为数组,这样你可以有重复的钥匙。主要方法:初始字典,包括所有相关的每一个单词字;使用地图和减少递归链的扩展;基于等效过滤链。
First of all, I would store the relationships as arrays so that you can have duplicate "keys." Key methods: an initial dictionary including every word related to each individual word; a recursive chain expander using map and reduce; filtering chains based on equivalency.
Array.prototype.getUnique = function(){
var u = {}, a = [];
for(var i = 0, l = this.length; i < l; ++i){
if(u.hasOwnProperty(this[i])) {
continue;
}
a.push(this[i]);
u[this[i]] = 1;
}
return a;
}
var links = {};
var pairs = [
["car", "wheel"],
["wheel", "tyre"],
["bed", "sheets"],
["guitar", "strings"],
["guitar", "pickup"],
["rubber", "tyre"],
["truck", "wheel"],
["pickup", "car"]
];
pairs.map(function(pair) {
links[pair[0]] = links[pair[0]] || [];
links[pair[1]] = links[pair[1]] || [];
links[pair[0]].push(pair[1]);
links[pair[1]].push(pair[0]);
});
var append = function(list) {
var related = list.map(function(item) {
return links[item];
}).reduce(function(listA, listB) {
return listA.concat(listB);
}).filter(function(item) {
// make sure related only includes new links
return list.indexOf(item) == -1
}).getUnique();
return related.length ? append(list.concat(related)) : list.concat(related);
};
var branches = [];
for( var word in links ) {
branches.push(append(links[word].concat(word)));
}
var compareArrays = function(listA, listB) {
if( listA.length != listB.length ) return false;
return listA.map(function(element) {
if( listB.indexOf(element) == -1 ) return 0;
return 1;
}).filter(function(el) {
return el == 1;
}).length == listA.length;
};
var _branches = branches;
var chains = branches.filter(function(branch1, i) {
var isUnique = _branches.filter(function(branch2) {
// are they equivalent
return compareArrays(branch1, branch2);
}).length == 1;
delete _branches[i];
return isUnique;
});
上一篇:是二叉搜索树平衡?是二叉