Assignment 8


Assorting Objects in an Array

  //Fruit Array


  //The fruits "objects" array
  var fruits = [
    { fruit: "apple", color: "red" },
    { fruit: "orange", color: "orange" },
    { fruit: "cherry", color: "red" },
    { fruit: "grape", color: "green" },
    { fruit: "strawberry", color: "red" },
    { fruit: "lemon", color: "yellow" },
    { fruit: "peach", color: "yellow" },
    { fruit: "kiwi", color: "green" },
    { fruit: "lime", color: "green" }
  ];

  //Sort by color, ascending...
  //Making sure all letters are lower case for the sort
  fruits.sort(function(a, b){
   var colorA=a.color.toLowerCase(), colorB=b.color.toLowerCase()
   if (colorA < colorB) //sort string ascending
    return -1
   if (colorA > colorB)
    return 1
   return 0 //default no sorting
  })
  console.log("Color sorted ascending first " + fruits);

  //Sort by fruit, ascending
  //Making sure all letters are lower case for the sort
  fruits.sort(function(a, b){
   var fruitA=a.fruit.toLowerCase(), fruitB=b.fruit.toLowerCase()
   if (fruitA < fruitB) //sort string ascending
    return -1
   if (fruitA > fruitB)
    return 1
   return 0 //default no sorting
  })
  console.log("Now fruit is sorted ascending also " + fruits);