Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructing alphabetized array of objects

I have an array of objects with a name property...

var myList = [{
  name: 'Apple'
}, {
  name: 'Nervousness',
}, {
  name: 'Dry'
}, {
  name: 'Assign'
}, {
  name: 'Date'
}]

Essentially, I am trying to create an array set up like this:

[{
  name: 'A',
  items: [{
    name: 'Apple'
  }, {
    name: 'Assign'
  }]
}, {
  name: 'D',
  items: [{
    name: 'Date',
  }, {
    name: 'Dry',
  }]
}, {
  name: 'N',
  items: [{
    name: 'Nervousness',
  }]
}];

Basically, my array of objects needs to be alphabetized, placed into a new object with a parent key/value of 'name' with the corresponding letter.

I can alphabetize them as follows...

myList.sort(function (a, b) {
  if (a.name < b.name) return -1;
  if (a.name > b.name) return 1;
  return 0;
});

Then I can create an array of the first letters...

var headerLetters = [];
angular.forEach(myList, function (item) {
  var firstLetter = item.name.charAt(0);
  if (headerLetters.indexOf(firstLetter) === -1) {
    headerLetters.push(firstLetter);
  }
});

But then this is where I am stuck... I can check for duplicate first letters, but then how would I iterate through my list of objects and push them into a new object array in alphabetical order?

like image 595
developthewebz Avatar asked Feb 13 '26 22:02

developthewebz


1 Answers

Assuming you sort them alphabetically first then you can always just check the latest item in the array and see if it matches the current name.

var headerLetters = [];
angular.forEach(myList, function(item) {
  var firstLetter = item.name[0];
  var lastObj = headerLetters[headerLetters.length - 1];
  if (!lastObj || lastObj.name !== firstLetter) {
    lastObj = {
      name: firstLetter,
      items: []
    };
    headerLetters.push(lastObj);
  }
  lastObj.items.push(item);
});
like image 168
Mike Cluck Avatar answered Feb 15 '26 10:02

Mike Cluck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!