3

I am trying to convert an array of objects that looks in this:

var allApps = [
 {
  title: "amazon",
  summary: "lorem ipsum"
 },
 {
  title: "facebook",
  summary: "lorem ipsum"
 },
 {
  title: "twitter",
  summary: "lorem ipsum"
 },
 {
  title: "flipp",
  summary: "lorem ipsum"
 }
]

Into something that looks like this:

var titles= {
A: [
    {      
     title: "amazon",
     summary: "lorem ipsum"
    }
],
F: [
     {
      title: "facebook",
      summary: "lorem ipsum"
     },
     {
      title: "flipp",
      summary: "lorem ipsum"
     }
],
T: [
     {
      title: "twitter",
      summary: "lorem ipsum"
     }
   ]
}

So far I have this:

        var letters = [];
        var titles = [];
        for (var i = 0; i < allApps.length; i++) {
            title = allApps[i].title;
            if (title=="") {
                continue;
            }
            var firstLetter = title.substring(0,1);
            var arrayWithFirstLetter = titles[firstLetter];
            if (arrayWithFirstLetter == null) {
                titles[firstLetter] = [];
                letters.push(firstLetter);
            };
        }

I essentially want to sort the apps based on the title property and push them into the array with the corresponding letter.

Right now my code takes the first letter of each of the titles and creates an array of arrays for each letter

duhaime
  • 25,611
  • 17
  • 169
  • 224
Mandalina
  • 446
  • 5
  • 22
  • Won't you run into a problem if you have, say `title: Twitter` and `title: Twitch` in different objects? – Scott Marcus Sep 04 '18 at 14:58
  • what do you mean? @ScottMarcus – Mandalina Sep 04 '18 at 14:59
  • 3
    It looks like you want to create keys (`A`, `F`, `T`) based on the first letter of each object's `title` key. Your desired output needs to be an object (you currently have it as an array), but you can't have duplicate keys in an object. – Scott Marcus Sep 04 '18 at 15:00
  • @ScottMarcus Exactly, I don't want duplicate keys. Take F for example, I want the F array to contain both objects with titles starting with F – Mandalina Sep 04 '18 at 15:02
  • @ScottMarcus Why duplicate keys? There will only be one `A`, `B`, `C`, ... - just as it is now for `F` with `facebook` and `flipp` – Andreas Sep 04 '18 at 15:02
  • 1
    Possible duplicate of [What is the most efficient method to groupby on a JavaScript array of objects?](https://stackoverflow.com/questions/14446511/what-is-the-most-efficient-method-to-groupby-on-a-javascript-array-of-objects) – Andreas Sep 04 '18 at 15:03
  • _So far I have this_.... That piece of code doesn't run without erros. Can you, please provide a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) if possible? – lealceldeiro Sep 04 '18 at 15:07

3 Answers3

1

How about:

var allApps = [
 {
  title: "amazon",
  summary: "lorem ipsum"
 },
 {
  title: "facebook",
  summary: "lorem ipsum"
 },
 {
  title: "twitter",
  summary: "lorem ipsum"
 },
 {
  title: "flipp",
  summary: "lorem ipsum"
 }
]

var d = {};
for (var i=0; i<allApps.length; i++) {
  var l = allApps[i].title.substring(0,1);
  // ensure object has key
  if (!d[l]) d[l] = [];
  d[l].push(allApps[i]);
}

console.log(d)

This logs:

{
  a: [
    { title: 'amazon', summary: 'lorem ipsum' }
  ],
  f:[
    { title: 'facebook', summary: 'lorem ipsum' },
    { title: 'flipp', summary: 'lorem ipsum' }
  ],
  t: [
    { title: 'twitter', summary: 'lorem ipsum' }
  ]
}

The idea here is we just loop over allApps, examine the first letter of the title attribute on the current member of that array, then check if that letter is already a key in our new dictionary, d. If not, we add that letter as a key in d. Then we add the current element from allApps to the list of values for that key. That's it!

duhaime
  • 25,611
  • 17
  • 169
  • 224
1

Use the reduce function and from the current object get the first character. This first character is going to be. If this key exist then update it's value

var allApps = [{
    title: "amazon",
    summary: "lorem ipsum"
  },
  {
    title: "facebook",
    summary: "lorem ipsum"
  },
  {
    title: "twitter",
    summary: "lorem ipsum"
  },
  {
    title: "flipp",
    summary: "lorem ipsum"
  }
]
let k = allApps.reduce(function(acc, curr) {
  let getFirstChar = curr.title.charAt(0).toUpperCase();

  if (acc[getFirstChar] === undefined) {
    acc[getFirstChar] = [];
  }
  acc[getFirstChar].push(curr)
  return acc;



}, {})
console.log(k)
brk
  • 48,835
  • 10
  • 56
  • 78
0

You don't need the variable letters. You should be pushing onto titles[firstletter].

And titles should be initialized as an object, not an array.

var allApps = [
 {
  title: "amazon",
  summary: "lorem ipsum"
 },
 {
  title: "facebook",
  summary: "lorem ipsum"
 },
 {
  title: "twitter",
  summary: "lorem ipsum"
 },
 {
  title: "flipp",
  summary: "lorem ipsum"
 }
];

var titles = {};
for (var i = 0; i < allApps.length; i++) {
  title = allApps[i].title;
  if (title == "") {
    continue;
  }
  var firstLetter = title.substring(0, 1).toUpperCase();
  if (!titles[firstLetter]) {
    titles[firstLetter] = [];
  };
  titles[firstLetter].push(allApps[i]);
}

console.log(titles);
Barmar
  • 741,623
  • 53
  • 500
  • 612