-1

I build an object (jQuery) like this:

var arr = { items : [] };
$.each(arr, (function (key, value) {
    arr.items.push({
         id : key,
         param1 : "hello",
         param2 : "world !"
    });
});

What I want to do is to check before I push if I already have a record in my object with at least one identical id, param1 or param2.

I know I could insert an $.each before I push but there is probably a cleaner solution?

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
user3546553
  • 63
  • 10
  • 3
    Your array syntax is invalid, you can't have `key:value` inside `[...]`. – Barmar Jun 13 '14 at 08:11
  • 1
    u can use jQuery.inArray – sakir Jun 13 '14 at 08:13
  • Your `param1` and `param2` are always the same, so they will always be identical. Should those properties come from `value`? – Barmar Jun 13 '14 at 08:15
  • @Barmar, sorry, my mistake i corrected. This is just an example, param1 and param2 can be identical like they can be different – user3546553 Jun 13 '14 at 08:15
  • @sakir how should i use $.inArray? Thanks. – user3546553 Jun 13 '14 at 08:16
  • Why is your array an object with another array inside it? Don't you mean `var arr = [];`? – Liam Jun 13 '14 at 08:17
  • @Liam, can you write and example about how i should write my array? I always use to do like this – user3546553 Jun 13 '14 at 08:18
  • also `items.push` will produce a syntax error. again, don't you mean `arr.items.push`. May I suggest you get **this** code working before elaborating on it. Here's [inArray](http://api.jquery.com/jquery.inarray/) docs – Liam Jun 13 '14 at 08:20
  • [Array declaration in JavaScript](http://stackoverflow.com/questions/931872/what-s-the-difference-between-array-and-while-declaring-a-javascript-ar) – Liam Jun 13 '14 at 08:24
  • This is correct Liam, but thats because i tipped to fast, my actual code in my project. – user3546553 Jun 13 '14 at 08:37

1 Answers1

3

Use objects to keep track of the values that have previously been seen.

ids = {};
param1s = {};
param2s = {};
$.each(array, function(key, value) {
    if (!(key in ids || value.param1 in param1s || value.param2s in param2s)) {
        items.push({
            id: key,
            value1: value.param1,
            value2: value.param2
        });
        ids[key] = true;
        param1s[value.param1] = true;
        param2s[value.param2] = true;
    }
});
Barmar
  • 741,623
  • 53
  • 500
  • 612