Livio Zanol Puppim
Livio Zanol Puppim

Reputation: 71

Javascript - Inserting unique elements in Array: Multidimensional check x Temporary unidimensional array

I don't know if it's a stupid question, but here it comes:

Imagine an array of unordered objects like: [{id:4, name:"a"},{id:2, name:"b"},{id:3, name:"ee"},{id:1, name:"fe"},.....].

This array is dinamically created inside a loop using javascript, but, everytime I'll push something to the array I must check if an object with the same id exists and only pushs the newones.

Which one is faster:

1) At every loop check manualy the entire array.

or

2) Create a temporary unidimensional array only with ids and use indexOf to check if the new object id is present and then, if not present at the temporary array, add it to the original array.

Upvotes: 0

Views: 95

Answers (1)

ikrabbe
ikrabbe

Reputation: 1929

How about

var a = []
var o = { id:10, name:"xyz" }
if(typeof a[o.id]=="undefined") {
    a[o.id] = { name:o.name }
}

? That should be fastest for most machines. Or to not change your object structure

a[o.id] = { id:o.id, name:o.name }

But the better approach would be

function getA(i) { if (typeof a[i] == "undefined") return null;
    return { id:i, name:a[i].name }; }

Upvotes: 1

Related Questions