Black
Black

Reputation: 5367

Array concat returns empty array

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?

Upvotes: 8

Views: 6362

Answers (2)

Pac0
Pac0

Reputation: 23174

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.

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68393

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 )

Upvotes: 21

Related Questions