1

I have the following array:

>>> var cars = new Array;
undefined

>>> cars[5] = 'Volvo';
"Volvo"

>>> cars[10] = 'Honda';
"Honda"

>>> cars
[undefined, undefined, undefined, undefined, undefined, "Volvo", undefined, undefined, undefined, undefined, "Honda"]

>>> cars.length
11

Is there a way to get new array out of cars that is not sparse - like ['Volvo', 'Honda']. Actually in my case even the order of the values would not matter.

Of course, I can do it with a loop but I'm looking for more elegant solution. jQuery is also an option!

ddinchev
  • 33,683
  • 28
  • 88
  • 133
  • Why do you need to specify keys explicitly if you don't care of them? – zerkms Jan 01 '13 at 23:08
  • 1
    Already answered: http://stackoverflow.com/questions/281264/remove-empty-elements-from-an-array-in-javascript – Alexander Christiansson Jan 01 '13 at 23:09
  • Well, I index my array by the item ids, each id points to an object. I need to supply the objects as simple list to 3rd party library. – ddinchev Jan 01 '13 at 23:10
  • you can also use an object like a sparse array. use $.each() to iterate through the object. – Levi Jan 01 '13 at 23:11
  • Just as Levi I would suggest using an object. You do not even need a library to iterate the object, on modern browsers you can just use a for in loop. – inta Jan 01 '13 at 23:15

2 Answers2

3

jQuery.map does array flattening automatically so:

var flattenedArr = $.map(cars, function(v) {
    return v;
});

Fiddle

Fabrício Matté
  • 69,329
  • 26
  • 129
  • 166
  • Does it remove any falsy values or just undefined? Edit: nvm, I saw the fiddle now :) – ddinchev Jan 01 '13 at 23:17
  • And that's because jQuery [internally does loose comparison](https://github.com/jquery/jquery/blob/1.8-stable/src/core.js#L718) with `null` so `null == undefined //true` – Fabrício Matté Jan 01 '13 at 23:22
2
cars = $.grep(arr, function(n){
    return(n);
});

This just leaves the defined elements of your array and ignores the undefined ones.

more info

reneraab
  • 61
  • 3
  • 2
    This is a good solution, just one note: falsy values will be eliminated from the array this way. I guess `return typeof n !== 'undefined';` will do better in that aspect. – Fabrício Matté Jan 01 '13 at 23:14