I have an array with items and I want to group them according the first letter but when I push the item to the array it shows empty "Array[0]" while there are clearly items in it.
Apparently I'm doing something wrong but i have no idea what.
var group = [];
var alphabetArray = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
alphabetArray.forEach(function(letter) {
group[letter] = group[letter] || [];
group[letter].push({
key: letter,
letter
});
});
console.log(group);
3 Answers 3
Arrays are designed to hold an ordered set of data represented by property names which are integers.
You are assigning property names which are letters.
Arrays are not designed to hold that kind of data and console.log doesn't display those properties for arrays.
Don't use an array. Use an object. Objects are designed to hold unordered data with arbitrary property names. If order matters, then you might want to use a Map instead.
1 Comment
i is in the range +0 ≤ i < 2^32-1. :-)You are looking to create an object instead of an array. Change the [] to {}
An Array expects an int as index, the object can take a string
var group = {}; // Object instead of Array
var alphabetArray = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
alphabetArray.forEach(function(letter) {
group[letter] = group[letter] || [];
group[letter].push({
key: letter,
letter
});
});
console.log(group);
2 Comments
I guess you want to transform each letter to structure. I f so, you need Array.map:
var alphabetArray = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
var group = alphabetArray.map(function(letter) {
return {
[letter]: letter
};
});
console.log(group);
AB, just for first two characters. I still have no idea what exactly are you looking for.