我有一个类似于以下对象的数组:
var routeArr = [ {start: 1,end: 2},{start: 1,end: 3},end: 4},{start: 2,end: 1},{start: 3,{start: 4,end: 1} ];
这些对象表示行的起点和终点,因此{start:1,end:2}和{start:2,end:1}表示相同的行.
我试图从数组中删除所有重复的行,并找不到有效或优雅的方法来做到这一点.我已经尝试了一个嵌套循环但是,我被告知这是不好的做法(我的实现有错误,而且它只是丑陋).
for(var i = 0,numRoutes = routeArr.length; i < numRoutes; i++) { var primaryRoute = routeArr[i]; for(var j = 0; j < numRoutes; j++) { var secondRoute = routeArr[j]; if(primaryRoute.start === secondRoute.end && primaryRoute.end === secondRoute.start) { routeArr.splice(j,1); continue; } } }
有人可以提供建议吗?
解决方法
在javascript中创建一个对象/映射并保留唯一对象的索引,将“min(start,end):max(start,end)”存储为键,索引存储为值.以下是javascript中您的问题的实现:
// your initial array var routeArr = [ {start: 1,end: 1} ]; // map where we will store key => value where key is a joined start,end of your array's item and value is an item index var keyToRouteIndexMap = {}; for (var i in routeArr){ // calculating min and max from start and end to understand {start:1,end:2} and {start:2,end:1} object as duplicates var min = Math.min(routeArr[i].start,routeArr[i].end); var max = Math.max(routeArr[i].start,routeArr[i].end); // unique key var key = min+':'+max; if (!keyToRouteIndexMap.hasOwnProperty(key)){ keyToRouteIndexMap[key] = i; } } for(var key in keyToRouteIndexMap){ if(keyToRouteIndexMap.hasOwnProperty(key)){ console.log(routeArr[keyToRouteIndexMap[key]]); } }