adbarads adbarads - 7 months ago 19
Javascript Question

lodash sorting an array of objects in javascript

I have an array of objects response from the server, I am trying to sort by uid in ascending order, while keeping the entire array intact for the

data
array. Meaning in the
data
array there are 2 elements. I am trying to look at the uid in one of the arrays it is in of all the elements within the array and determine the order of how the elements should be placed within the
data
array.

I have tried the following using lodash, but it doesn't seem to work, but I feel I'm getting close and would like some assistance:

// sort by:
console.log(res.results[0].data[0].row[1].uid)

_.forEach(res.results, function(obj) {
_.forEach(data, function(anotherObj) {
_.forEach(row, function(row) {
data.row = _.sortBy(data.row, function(row) {
return row[1].uid;
});
});
});
});


Here is the array of objects returned from server:

var res = {
results: [{
columns: ['large', 'medium', 'small'],
data: [{
row: [{
sid: 13,
tid: 427
},
{
uid: 69,
vid: 450,
wid: 65
},
null],
multirow: {
nodule: [{
xid: '427',
properties: {
yid: 13,
zid: 427
}
},
{
aid: '450',
properties: {
uid: 69,
bid: 450,
cid: 65
}
}]
}
},
{
row: [{
sid: 13,
tid: 427
},
{
vid: 432,
uid: 65,
wid: 61
},
null],
multirow: {
nodule: [{
xid: '427',
properties: {
yid: 13,
zid: 427
}
},
{
aid: '432',
properties: {
bid: 432,
uid: 65,
cid: 61
}
}]
}
}]
}],
errors: []
};

Answer

You don't need that many loops:

_.forEach(res.results, function(result) {
  result.data = _.sortBy(result.data, function(datum) {
    return datum.row[1].uid;
  });
});

You only need to iterate over the results, each of which might have a data array that you are going to sort. The sortBy callback then takes each of the elements of that array and is supposed to return the value to compare.

Comments