gpt4 book ai didi

Javascript 将链接的键值分组到数组中

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:02:22 25 4
gpt4 key购买 nike

您好,我在 json key:value、key:value 等格式中有很长的键值对列表

car <--> wheel
wheel <--> tyre
bed <--> sheets
guitar <--> strings
guitar <--> pickup
tyre <--> rubber

我想要的是将所有关系分组到数组中,无论多远都是这样

[car, wheel, tyre, rubber]
[guitar, strings, pickup]
[bed, sheets]

使用 Javascript 执行此操作的有效方法是什么?

最佳答案

首先,我会将关系存储为数组,这样您就可以拥有重复的“键”。关键方法:一个初始字典,包括与每个单独单词相关的每个单词;使用 map 和 reduce 的递归链扩展器;基于等价性过滤链。

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;
});

关于Javascript 将链接的键值分组到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12046080/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com