-2

I want to create a JSON object that is organized alphabetically as follows:

var Dictionary = {};
var AlphabetString = "abcdefghijklmnopqrstuvwxyz";
for (x in AlphabetString) {
  Dictionary[x] = new Array();
}
var TestingString = ["apples, bannans, carrots, dice"];
for (x in TestingString) {
  Dictionary[TestingString.charAt(0)].push(TestingString);
}

So that Dictionary at each alphabet will give me an array of strings that have the same first letter as the identifier i.e. in my example Dictionary["a"] = ["apples"]. Is this the correct way to go about this?

Ayan
  • 2,300
  • 1
  • 13
  • 28
IntegrateThis
  • 853
  • 2
  • 16
  • 39

3 Answers3

1

You shouldn't use for...in loops to iterate array-like objects like arrays or strings.

And TestingString should be an array of words.

I would use something like this (possibly checking if firstChar is the empty string):

var dictionary = Object.create(null);
var testingArray = ["apples", "bannans", "carrots", "dice", "abc"];
for (var i=0; i<testingArray.length; ++i) {
  var firstChar = testingArray[i].charAt(0);
  if(!(firstChar in dictionary)) dictionary[firstChar] = [];
  dictionary[firstChar].push(testingArray[i]);
}
console.log(dictionary);

In ES6 you can iterate with for...of.

Community
  • 1
  • 1
Oriol
  • 274,082
  • 63
  • 437
  • 513
1

As referred here, for in is a bad idea here. But in case if you still want to cling to it, there`s how you can do it.

var Dictionary = {},
  elem, index;
var AlphabetString = "abcdefghijklmnopqrstuvwxyz";
var TestingString = ["apples", "bannans", "carrots", "dice"];
for (x in TestingString) {
  elem = TestingString[x];
  index = elem.charAt(0);
if (!Dictionary[index]) {
  Dictionary[AlphabetString[x]] = [];
}
Dictionary[index].push(elem);
}

console.dir(Dictionary);
Community
  • 1
  • 1
Ayan
  • 2,300
  • 1
  • 13
  • 28
0

You can also do it with array methods

var AlphabetString = "abcdefghijklmnopqrstuvwxyz";
var Dictionary  = AlphabetString.split('').reduce( (res, curr) =>{
  res[curr] = []
  return res
}, {})

var TestingString = "apples, bannans, carrots, dice";
res = TestingString.split(/, /).forEach( item => Dictionary[item[0].toLowerCase()].push(item))
eltonkamami
  • 5,134
  • 1
  • 22
  • 30