Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array concat returns empty array

Tags:

javascript

I'm adding several items to an array using concat in an event-handler as follows:

var selectedValues = [];
$.each($('#selected-levels').data("kendoListBox").dataSource.data(), function(i, item) {
    selectedValues.concat([ item.id ])
});

return {
    "selected" : selectedValues
};

this always returns {level-selected: Array(0)} even though I have checked that there are some items in the dataSource (by stepping through with debugger)

why don't the items appear in the array?

like image 376
Black Avatar asked Mar 13 '18 09:03

Black


People also ask

Does array concat return a new array?

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

Does concat mutate original array?

concat() is used to merge two or more arrays. This method does not mutate the original array, but instead returns a new array populated with elements of all the arrays that were merged.

What happens when an array is empty?

An empty array will have 0 elements inside of it.

How do you concatenate an array?

In order to combine (concatenate) two arrays, we find its length stored in aLen and bLen respectively. Then, we create a new integer array result with length aLen + bLen . Now, in order to combine both, we copy each element in both arrays to result by using arraycopy() function.


2 Answers

concat doesn't mutate the array, you need to set the value back to selectedValues

selectedValues = selectedValues.concat([ item.id ])

Or use push

selectedValues.push( item.id )
like image 179
gurvinder372 Avatar answered Oct 30 '22 21:10

gurvinder372


Ironically, the answer was already hidden in your question, in your question title more exactly.

Actually concat returns the correct new array you want... you just never used the return value !

You have to be aware that the array is not modified in place, but a fresh copy is returned.

So selectedValues.concat([ item.id ]) should be replaced by selectedValues = selectedValues.concat([ item.id ]) if you want to do anything.

like image 41
Pac0 Avatar answered Oct 30 '22 22:10

Pac0