Get unique values from 2d array javascript
Ngày đăng:
20/09/2022
Trả lời:
0
Lượt xem:
108
If you can use lodash, this is good solution (note that based on your platform, the "require" keyword can differ, this is how to use it in Node.js):
This would be output
If order of elements in array matter to you, i.e. this array [ 'a', 'b', 'c' ] is considered different than this one ['b', 'a', 'c'], all you need is to delete the "sort" part :
This would be output : PreviousNext Javascript Source CodeThe Javascript source code to do "Javascript Array get distinct values in a 2D array" is var items = [['al','bv','sd'], ['al','cc','ab'], ['cv','vv','sw'], ['al','bv','sd'] ];// w w w . d e mo 2 s . c o m function arrays_equal(a,b) { return !!a && !!b && !(aArray.prototype.unique = function() { var a = []; for (var i = 0, l = this.length; i <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- w w w . d e m o 2 s. c o m--> <body> <script type='text/javascript'> var items = [['al','bv','sd'], ['al','cc','ab'], ['cv','vv','sw'], ['al','bv','sd'] ]; function arrays_equal(a,b) { return !!a && !!b && !(a<b || b<a); } Array.prototype.unique = function() { var a = []; for (var i = 0, l = this.length; i<l; i++) { for (var j = i + 1; j < l; j++) if (arrays_equal(this[i], this[j])) j = ++i; a.push(this[i]); } return a; }; var ret = items.unique(); console.log(ret); //solution 2 var items = [['al','bv','sd'], ['al','cc','ab'], ['cv','vv','sw'], ['al','bv','sd'] ]; for (var i=0; i<items.length; i++) { var listI = items[i]; loopJ: for (var j=0; j<items.length; j++) { var listJ = items[j]; if (listI === listJ) continue; //Ignore itself for (var k=listJ.length; k>=0; k--) { if (listJ[k] !== listI[k]) continue loopJ; } // At this point, their values are equal. items.splice(j, 1); } } document.body.innerHTML = items.join(' |