I have the following 2D array
var items = [['al','bv','sd'],
['al','cc','ab'],
['cv','vv','sw'],
['al','bv','sd']
];
I need a function which will return me a similar array but with distinct values. For example, in the above array, ['al','bv','sd']
happens twice.
I would like the function to return me:
var items = [['al','bv','sd'],
['al','cc','ab'],
['cv','vv','sw']
];
Quick and dirty solution, assuming the data is small.
On each iteration, convert the row to a string. Use a dictionary to store the string with a value of True, if it is not already in the map. Also, add it to your output array. If it is already in the dictionary, go to the next item.
Example:
var d = {};
var out = [];
for( var i = 0; i < items.length; i++ ) {
var item = items[i];
var rep = item.toString();
if (!d[rep]) {
d[rep] = true;
out.push(item);
}
}
// out has the result
You have to loop two (or three times):
Loop again, through all "rows", from beginning to the end
Loop through all "columns":
.splice
method.Code:
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);
}
}
An unconventional but easier to code version
var items = [['al','bv','sd'],
['al','cc','ab'],
['cv','vv','sw'],
['al','bv','sd']
];
var temp = {};
for ( var i in items ) {
var serialized = JSON.stringify(items[i]);
if ( temp[serialized] ) {
items.splice( i, 1 );
continue;
}
temp[serialized] = true;
}
Try it here! http://jsfiddle.net/y3ccJ/1/
More conventional option:
var items = [['al','bv','sd'],
['al','cc','ab'],
['cv','vv','sw'],
['al','bv','sd']
];
var results = [];
loop: for ( var i in items ) {
compare: for ( var j in results ) {
for ( var k in items[i] ) {
if ( items[i][k] !== results[j][k] ) {
break compare;
}
}
continue loop;
}
results.push( items[i] );
}
http://jsfiddle.net/xhrd6/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With