-4

Sort the below dictionary/ array key using Javascript and output the information in key:value format on a Polymer interface. The entire numeric key should be sorted in an ascending order and all the alpha keys should be sorted in ascii, ascending order.

Dictionary = {'34': 'thirty-four', '90': 'ninety',
'91': 'ninety-one'' 21': 'twenty-one',
'61': 'sixty-one', '9': 'nine',
'2': 'two', '6': 'six', '3': 'three ',
'8': 'eight', '80': 'eighty', '81': 'eighty-one',
'Ninety-Nine':  '99', 'nine-hundred':  '900',}
melpomene
  • 84,125
  • 8
  • 85
  • 148
  • 1
    We don't do your homework. – str Aug 13 '16 at 10:21
  • so far i have managed to do this but it still doesn't sort please help – Prince Bob Kimani Aug 13 '16 at 10:21
  • You have managed to do what? If you you want help with your code, then show your code. – str Aug 13 '16 at 10:23
  • var myObj = { 34:'thirty-four', 90:'ninety', 91: 'ninety-one', 61: 'sixty-one', 2: 'two', 9: 'nine', 21: 'twenty-one', 3: 'three', 6: 'six', 8: 'eight', 80: 'eighty', 81: 'eighty-one', 'Ninety-nine' :99, 'nine-hundred' :900, }, keys = [], k, i, len; for (k in myObj) { if (myObj.hasOwnProperty(k)) { keys.push(k); } } keys.sort(); len = keys.length; for (i = 0; i <= len; i++) { k = keys[i]; alert(k + ':' + myObj[k]); } – Prince Bob Kimani Aug 13 '16 at 10:26
  • not homework....its an error i ran into and the sorting wont work – Prince Bob Kimani Aug 13 '16 at 10:28
  • Curious - it's a valid question, and someone voted a working answer down - odd :) @PrinceBobKimani try the answer below? Not sure what you need on the text sorting though - clarification? – MyStream Aug 13 '16 at 10:31

1 Answers1

-1
/**
 this code has a trailing comma that should be removed
 and it has a double quote and missing comma
 **/
    var Dictionary = {'34': 'thirty-four', '90': 'ninety', '91': 'ninety-one'' 21': 'twenty-one', '61': 'sixty-one', '9': 'nine', '2': 'two', '6': 'six', '3': 'three ', '8': 'eight', '80': 'eighty', '81': 'eighty-one', 'Ninety-Nine': '99', 'nine-hundred': '900',}
    var Dictionary = {
'34': 'thirty-four',
'90': 'ninety',
'91': 'ninety-one',
'21': 'twenty-one',
'61': 'sixty-one',
'9': 'nine',
'2': 'two',
'6': 'six',
'3': 'three ',
'8': 'eight',
'80': 'eighty',
'81': 'eighty-one',
'Ninety-Nine': '99',
'nine-hundred':'900'
};

Sort JavaScript object by key

var newDictionary = {}, keys = Object.keys(Dictionary), i=-1, len = keys.length;
keys.sort();
while (++i < len) {
  newDictionary[keys[i]] = Dictionary[keys[i]];
}
console.log(newDictionary);

// something along this line?

//This gives the following out put:
Object { 2: "two", 3: "three ", 6: "six", 8: "eight", 9: "nine", 21: "twenty-one", 34: "thirty-four", 61: "sixty-one", 80: "eighty", 81: "eighty-one", 90 : "ninety", 91 : "ninety-one", "Ninety-Nine" : "99", "nine-hundred" : "900" }
Community
  • 1
  • 1
MyStream
  • 2,533
  • 1
  • 16
  • 33