0

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.

1 Answer 1

0

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/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.