Simple ways:
var arr = [1,2,,3,,-3,null,,0,,undefined,4,,4,,5,,6,,,,];
arr.filter(n => n)
// [1, 2, 3, -3, 4, 4, 5, 6]
arr.filter(Number)
// [1, 2, 3, -3, 4, 4, 5, 6]
arr.filter(Boolean)
// [1, 2, 3, -3, 4, 4, 5, 6]
or - (only for single array items of type "text")
['','1','2',3,,'4',,undefined,,,'5'].join('').split('');
// output: ["1","2","3","4","5"]
or - Classic way: simple iteration
var arr = [1,2,null, undefined,3,,3,,,0,,,[],,{},,5,,6,,,,],
len = arr.length, i;
for(i = 0; i < len; i++ )
arr[i] && arr.push(arr[i]); // copy non-empty values to the end of the array
arr.splice(0 , len); // cut the array and leave only the non-empty values
arr // [1,2,3,3,[],Object{},5,6]
via jQuery:
var arr = [1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,];
arr = $.grep(arr,function(n){ return n == 0 || n });
arr // [1, 2, 3, 3, 0, 4, 4, 5, 6]
UPDATE - just another fast, cool way (using ES6):
var arr = [1,2,null, undefined,3,,3,,,0,,,4,,4,,5,,6,,,,],
temp = [];
for(let i of arr)
i && temp.push(i); // copy each non-empty value to the 'temp' array
arr = temp;
arr // [1, 2, 3, 3, 4, 4, 5, 6]
Remove empty values
['foo', '',,,'',,null, ' ', 3, true, [], [1], {}, undefined, ()=>{}].filter(String)
// ["foo", null, " ", 3, true, [1], Object {}, undefined, ()=>{}]
Best Answer
If you'd like a version on npm, array-move is the closest to this answer, although it's not the same implementation. See its usage section for more details. The previous version of this answer (that modified Array.prototype.move) can be found on npm at array.prototype.move.
I had fairly good success with this function:
Note that the last
return
is simply for testing purposes:splice
performs operations on the array in-place, so a return is not necessary. By extension, thismove
is an in-place operation. If you want to avoid that and return a copy, useslice
.Stepping through the code:
new_index
is greater than the length of the array, we want (I presume) to pad the array properly with newundefined
s. This little snippet handles this by pushingundefined
on the array until we have the proper length.arr.splice(old_index, 1)[0]
, we splice out the old element.splice
returns the element that was spliced out, but it's in an array. In our above example, this was[1]
. So we take the first index of that array to get the raw1
there.splice
to insert this element in the new_index's place. Since we padded the array above ifnew_index > arr.length
, it will probably appear in the right place, unless they've done something strange like pass in a negative number.A fancier version to account for negative indices:
Which should account for things like
array_move([1, 2, 3], -1, -2)
properly (move the last element to the second to last place). Result for that should be[1, 3, 2]
.Either way, in your original question, you would do
array_move(arr, 0, 2)
fora
afterc
. Ford
beforeb
, you would doarray_move(arr, 3, 1)
.