How to remove duplicates from multidimensional array? [closed]

匿名 (未验证) 提交于 2019-12-03 01:12:01

问题:

I have a multidimensional array:

[[7,3], [7,3], [3,8], [7,3], [7,3], [1,2]] 

Is there any smart way to remove duplicated elements from this? It should return such array:

[[7,3], [3,8], [1,2]] 

Thanks!

回答1:

arr = [[7,3], [7,3], [3,8], [7,3], [7,3], [1,2]];  function multiDimensionalUnique(arr) {     var uniques = [];     var itemsFound = {};     for(var i = 0, l = arr.length; i 

Explaination:

Like you had mentioned, the other question only dealt with single dimension arrays.. which you can find via indexOf. That makes it easy. Multidimensional arrays are not so easy, as indexOf doesn't work with finding arrays inside.

The most straightforward way that I could think of was to serialize the array value, and store whether or not it had already been found. It may be faster to do something like stringified = arr[i][0]+":"+arr[i][1], but then you limit yourself to only two keys.



回答2:

This requires JavaScript 1.7:

var arr = [[7,3], [7,3], [3,8], [7,3], [7,3], [1,2]];  arr.map(JSON.stringify).reverse().filter(function (e, i, a) {     return a.indexOf(e, i+1) === -1; }).reverse().map(JSON.parse) // [[7,3], [3,8], [1,2]] 


回答3:

var origin = [[7,3], [7,3], [3,8], [7,3], [7,3], [1,2]];  function arrayEqual(a, b) {     if (a.length !== b.length) { return false; }     for (var i = 0; i 

http://jsfiddle.net/2UQH6/



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!