ReynierPM ReynierPM - 21 days ago 5
Javascript Question

How to create a multidimensional array in Javascript and avoid duplicates?

I have the following HTML:

<input type="text" name="inp1" id="inp1" />
<input type="text" name="inp2" id="inp2" />
<input type="text" name="inp3" id="inp3" />

<input type="submit" value="Send" id="clickMe" />


Each time I click on the submit button I should add the values of each
inp*
to an array so I end up with something like this:

[
['inp1' => val1, 'inp2' => val2, 'inp3' => val3],
['inp1' => val10, 'inp2' => val20, 'inp3' => val30],
['inp1' => val11, 'inp2' => val21, 'inp3' => val31],
['inp1' => val12, 'inp2' => val22, 'inp3' => val32]
]


After reading this article I think I could do the following:

var obj = {};
var item = [];

$('#clickMe').click(function() {
item.push(
$('#inp1').val(),
$('#inp2').val(),
$('#inp3').val()
);
});


But the solution above will end up with a lineal array and not what I want (example here on Fiddle). I have read here and here but I am getting confused.

Also I shouldn't have repeated elements so this:

[
['inp1' => val1, 'inp2' => val2, 'inp3' => val3],
['inp1' => val1, 'inp2' => val2, 'inp3' => val3]
]


Is invalid. So, how is the right way to deal with this and get a multidimensional array?. Can any give me some help and leave an example so I can get this?

EDIT: As suggested the code should be compatible with most of the browser out there and as for IE should be IE9+

Answer

You could maintain a Set, which is more designed for this purpose than using object properties:

var list = new Set(); // helper object to avoid duplicates
var items = []; // the real 2D array

$('#clickMe').click(function() {
    var item = [
        $('#inp1').val(),
        $('#inp2').val(),
        $('#inp3').val()
    ];
    var key = JSON.stringify(item);
    if (list.has(key)) return; // skip
    list.add(key);
    items.push(item);
    return false; // to avoid that the form submits.
});

If you have many more input elements, it might be worth it to get their values via a loop:

var item = $('form input[type=text]').map(function () { 
    return $(this).val(); 
}).get();

When support for older browsers is needed

... then Sets are not an option. Use a plain object instead:

var list = {}; // helper object to avoid duplicates
var items = []; // the real 2D array

$('#clickMe').click(function() {
    var item = [
        $('#inp1').val(),
        $('#inp2').val(),
        $('#inp3').val()
    ];
    var key = JSON.stringify(item);
    if (list[key] === 1) return; // skip
    list[key] = 1;
    items.push(item);
    return false; // to avoid that the form submits.
});
Comments