-2

I have an array of countries sorted in alphabetical order. But I have to categorize them alphabetically using javascript.

Example array:

[Antigua,Barbados,China,Cuba,Dominican,Jamaica]

Expected output:

A: Antigua
B: Barbados
C: China,Cuba
D: Dominican
J: Jamaica

Any suggestions please?

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
Shivakumar H.G
  • 114
  • 2
  • 8
  • 2
    Please update whatever you've tried so far to achieve this. That way you can get better answers suiting your requirement. – Ms.Tamil Oct 22 '19 at 13:18

3 Answers3

2

Use Array#reduce that will return an object of type {[index: string]: Array<string>}, where the index represents the first letter, and the array holds all the countries starting with that letter.

var list = ["Antigua", "Barbados", "China", "Cuba", "Dominican", "Jamaica"];

var result = list.reduce(function(result, item) {
  var key = item[0]; // The key is the first letter of each country
  result[key] = result[key] || []; // create the array if it doesn't exist
  result[key].push(item); // add the element to the array
  return result;
}, {});

console.log("Object form:");
console.log(result);

var textResult = Object.entries(result).map(function([key, list]) {
  return `${key}: ${list.join()}`
}).join("\n\r");

console.log("Text form:");
console.log(textResult);
nick zoum
  • 7,216
  • 7
  • 36
  • 80
1

var obj = {}

var arr = ["Antigua","Barbados","China","Cuba","Dominican","Jamaica"]


arr.forEach(x => {
if (!obj[x[0]]) obj[x[0]] = [];
obj[x[0]] = obj[x[0]].concat([x]);
});

console.log(obj);

Object.keys(obj).forEach(x => console.log(`${x}: ${obj[x]}`))
chans
  • 5,104
  • 16
  • 43
  • What happened to `China`? – nick zoum Oct 22 '19 at 13:25
  • Added fix to above code, Its working now... Thanks for pointing out – chans Oct 22 '19 at 13:30
  • 1
    var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"]; var uniqueNames = []; $.each(names, function(i, el){ if($.inArray(el, uniqueNames) === -1) uniqueNames.push(el); }); –  Oct 22 '19 at 13:34
1

You can do it something like this:

let sourceData = ['Antigua','Barbados','China','Cuba','Dominican','Jamaica'];
const result = sourceData.reduce((a, c) => {
  let key = c.substring(0, 1);
  a[key] = a[key] || [];
  a[key].push(c);
  return a;
}, {})

console.log(result);
Alexander Nied
  • 12,804
  • 4
  • 25
  • 45
StepUp
  • 36,391
  • 15
  • 88
  • 148