Reputation: 5
I am looking for a simple way to check whether the values in a multidimensional array is duplicated in JavaScript.
Actually, I have a form with multiple inputs for Currency, Rate and Amount And I would like to call a JavaScript function to check before submit the form.
Here is the array
Array(
[0] => Array("CNY","2","1000")
[1] => Array("EUR","5","1200")
[2] => Array("USD","3","900")
[3] => Array("USD","8","1500")
[4] => Array("EUR","5","1200")
)
My purpose is to check the row cannot be exactly the same.
In my case, [1] => Array("EUR","5","1200") and [4] => Array("EUR","5","1200") is duplicate.
At the end, Key [1] and [4] will be returned by the function.
I will be glad if someone can give me some advice. Thank you very much.
Upvotes: 0
Views: 1680
Reputation: 9430
Use this function, it returns an array of keys of the values having duplicates in the containing array:
function find_keys_of_dupl(a){
var k = [];
for(var i in a){
for(var j in a){
if(i!=j && JSON.stringify(a[i]) == JSON.stringify(a[j])){
if(k.indexOf(i) < 0){
k.push(i);
}
}
}
}
return k;
}
var a = [["CNY","2","1000"],["EUR","5","1200"],["USD","3","900"],["USD","8","1500"],["EUR","5","1200"]];
console.log(find_keys_of_dupl(a));
Output:
["1", "4"]
Demo:
https://jsfiddle.net/r0kk0nuk/
Upvotes: 1