最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Loop through an array of objects and sort them - Stack Overflow

programmeradmin1浏览0评论

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 es 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 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 es 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?

Share Improve this question edited Jan 29, 2017 at 15:21 Polymorphic 4303 silver badges14 bronze badges asked Jan 29, 2017 at 11:58 divisionkillerdivisionkiller 3164 silver badges13 bronze badges 6
  • 1 Is there any reason why the internal properties order is important to you? what you should care is the order of the elements and not it's internal structure – Oscar Franco Commented Jan 29, 2017 at 12:11
  • 1 updated my answer with demo – Salih Şenol Çakarcı Commented Jan 29, 2017 at 12:16
  • @ospfranco no reason, I just want to learn it the right way. – divisionkiller Commented Jan 29, 2017 at 12:21
  • @SalihŞenolÇakarcı thank you I will check your solution – divisionkiller Commented Jan 29, 2017 at 12:21
  • @noone432423 in my opinion there is no right way to do this, in java you have an OrderedHashMap, there the order of the elements matter, but you are talking about object (read element) properties should not make any difference the order on which they appear, I believe your abstraction level needs to go one level above. – Oscar Franco Commented Jan 29, 2017 at 12:29
 |  Show 1 more ment

4 Answers 4

Reset to default 1

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

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 paring 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 pare 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 pare_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(pare_people); 

Done, array sorted!

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

Good luck.

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.

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

发布评论

评论列表(0)

  1. 暂无评论