Reputation: 231
I have an array of objects. For eg-
[{
aKey:2,
bKey:2,
cKey:3
}, {
bKey:2,
cKey:6
}, {
aKey:1,
bKey:6,
cKey:5
}, {
bKey:1,
cKey:4
}, {
bKey:6,
cKey:7
}]
So what I need to do is-
So the output will be-
[{
aKey:1,
bKey:6,
cKey:5
}, {
aKey:2,
bKey:2,
cKey:3
}, {
bKey:2,
cKey:6
}, {
bKey:1,
cKey:4
}, {
bKey:6,
cKey:7
}]
Upvotes: 2
Views: 378
Reputation: 42352
For sorting preferentially from aKey
to bKey
and then to cKey
, you can use this:
var array=[{aKey:2,bKey:2,cKey:3},{bKey:2,cKey:6},{aKey:1,bKey:6,cKey:5},{bKey:1,cKey:4},{bKey:6,cKey:7}]
var result = array.sort(function(hash) {
return function(a, b) {
return ((a.aKey || Infinity) - (b.aKey || Infinity))
|| ((a.bKey || Infinity) - (b.bKey || Infinity))
|| ((a.cKey || Infinity) - (b.cKey || Infinity))
}
}(Object.create(null)));
console.log(result);
.as-console-wrapper{top:0;max-height:100%!important;}
But you want
bKey:2
to come beforebKey:1
as for the last element that hasaKey
, the value ofbKey
is2
.
To adjust for this anomaly, without knowing which element is to follow once aKey
is done with (and extending to the case where bKey
is also done with too), you can do this - hash these anomaly keys and sort accordingly - see demo below:
var array=[{aKey:2,bKey:2,cKey:3},{aKey:1,bKey:6,cKey:5},{bKey:1,cKey:4},{bKey:6,cKey:7},{bKey:2,cKey:7},{bKey:2,cKey:6},{cKey:4},{cKey:7}]
var result = array.sort(function(hash) {
return function(a, b) {
// find the anomaly keys
a.aKey && !b.aKey && (hash.bkey = a.bKey);
a.bKey && !b.bKey && (hash.ckey = a.cKey);
// sort criteria
return ((a.aKey || Infinity) - (b.aKey || Infinity))
|| (((a.bKey != hash.bkey) - (b.bKey != hash.bkey)) || ((a.bKey || Infinity) - (b.bKey || Infinity)))
|| (((a.cKey != hash.ckey) - (b.cKey != hash.ckey)) || ((a.cKey || Infinity) - (b.cKey || Infinity)))
}
}(Object.create(null)));
console.log(result);
.as-console-wrapper{top:0;max-height:100%!important;}
Upvotes: 2
Reputation: 122047
You can use sort()
like this
var data = [{
aKey:2,
bKey:2,
cKey:3
}, {
bKey:2,
cKey:6
}, {
aKey:1,
bKey:6,
cKey:5
}, {
cKey:41
}, {
cKey:7
}, {
bKey:1,
cKey:4
}, {
bKey:6,
cKey:7
}]
data.sort(function(a, b) {
return ((b.aKey != undefined) - (a.aKey != undefined) || a.aKey - b.aKey) ||
((b.bKey != undefined) - (a.bKey != undefined) || ((a.bKey != 2) - (b.bKey != 2)) || a.bKey - b.bKey) ||
((b.cKey != undefined) - (a.cKey != undefined) || a.cKey - b.cKey)
})
console.log(data)
Upvotes: 2