3

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?

1 Answer 1

2

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);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Fantastic. Thank you very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.