divisionkiller
divisionkiller

Reputation: 316

Loop through an array of objects and sort them

I have an array containing some objects and I am trying to loop through it where I have data stored in the following order:

firstName: Alice
lastName: Wonderland
age:12

I am trying to loop, then to sort it in descending order where age: value should be in first position then > lastName: Wonderland comes and lastly firstName.

Here is my code until this moment

var data = {
  example1: [{
    firstName: 'Alice',
    lastName: 'Wonderland',
    age: 12
  }],
  example2: [{
    firstName: 'Thomas',
    lastName: 'Mathison',
    age: 14
  }],
  example3: [{
    firstName: 'David',
    lastName: 'Jacobsen',
    age: 18
  }]
};

for (var key in data) {
  var arr = data[key];
  for (var i = 0; i < arr.length; i++) {
    var obj = arr[i];
    for (var prop in obj) {
      if (obj.hasOwnProperty(prop)) {
        console.log(prop + ': ' + obj[prop]);
      }
    }
  }
}

I want to achieve the reverse order (descending) when I output the result in the console.log();:

age: 12,
lastName: 'Wonderland',
firstName: 'Alice'

age:14,
lastName: 'Mathison',
firstName: 'Thomas'

age:18,
lastName: 'Jacobsen',
firstName: 'David'

I am not sure about the sort function behavior. How should it work during the loop?

Any suggestions?

Upvotes: 4

Views: 4163

Answers (4)

Oscar Franco
Oscar Franco

Reputation: 6260

Apparently the question is not clear enough, people keep giving you sorting algorithms which I understand it is not what you are looking for, you want to change the internal order of the properties (which makes no sense, they have no 'order' they are part of a map, in any case, here is what I would do:

var data = {
  example1: [{
    firstName: 'Alice',
    lastName: 'Wonderland',
    age: 12
  }],
  example2: [{
    firstName: 'Thomas',
    lastName: 'Mathison',
    age: 14
  }],
  example3: [{
    firstName: 'David',
    lastName: 'Jacobsen',
    age: 18
  }]
};

for (var key in data) {
  var arr = data[key];
  var newArr = [];
  for (var i = 0; i < arr.length; i++) {
    var obj = arr[i];
    newArr.push({
      age: obj.age,
      firstName: obj.firstName,
      lastName: obj.lastName
    })
  }
  data[key] = newArr;
}

But again, what you are trying to do makes no sense, or at least according to the description.

Upvotes: 1

David Neto
David Neto

Reputation: 808

Sorting arrays of non-primitive data types (custom objects and data structures like in your case) require two steps. It's quite straightforward so follow along.

First you need to create a function capable of comparing two objects of your custom data structure according to your desired criteria.

Second, you provide this decision function to a sort function along with your array and it will use it to sort the array for you. Lets do it for your case:

First the compare function, a and b are objects from your custom structure. returning 1 means object a is "bigger", returning -1 means b is "bigger", returning 0 means that, according to your criteria, both are equal in "size". The order of the if statements bellow is naturally important and reflects the priorities you described:

age takes priority over names and last-name over first-name.

function compare_people(a, b) {
  if (a.age < b.age) {
    return -1;
  }

  if (a.age > b.age) {
    return 1;
  }

  if (a.lastName < b.lastName) {
    return -1;
  }

  if (a.lastName > b.lastName) {
    return 1;
  }

  if (a.firstName< b.firstName) {
    return -1;
  }

  if (a.firstName> b.firstName) {
    return 1;
  }

  return 0;
}

Now all you have to do is provide your criteria and array to javascript's sort function. In your case objects are stored inside the data array, so you do:

data.sort(compare_people); 

Done, array sorted!

Here you can study the concept more in depth https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Good luck.

Upvotes: 1

Use [].unshift() method

var result = [];
for (var key in data) {
  var arr = data[key];
  for (var i = 0; i < arr.length; i++) {
    var obj = arr[i];
    for (var prop in obj) {
      if (obj.hasOwnProperty(prop)) {
        result.unshift(prop + ': ' + obj[prop])
      }
    }
  }
}

console.log(result)

here is demo https://plnkr.co/edit/N4Zt28zh0A3MpwoOrzmZ?p=preview

Upvotes: 0

user3755154
user3755154

Reputation: 64

var data = {
  example1: [{
    firstName: 'Alice',
    lastName: 'Wonderland',
    age: 12
  }],
  example2: [{
    firstName: 'Thomas',
    lastName: 'Mathison',
    age: 14
  }],
  example3: [{
    firstName: 'David',
    lastName: 'Jacobsen',
    age: 18
  }]
};
var objectArray=[];
for (var key in data) {
  var arr = data[key];
  for (var i = 0; i < arr.length; i++) {
    var obj = arr[i];
       objectArray.push(obj);
  }
}
 objectArray.sort(function(element1,element2){
   return element2.age - element1.age
}); //now iterate over the array it is sorted in descending order

Upvotes: 1

Related Questions