How To Sort An Array In Javascript, But Save Results In Separate Array
I want to sort an array of objects based upon any of those object properties. But I want the original array left unchanged. Instead, I want to save the sort order of indexes in a s
Solution 1:
var source = [
{"a": 2, "b": 8, "c": 9},
{"a": 4, "b": 3, "c": 7},
{"a": 1, "b": 0, "c": 6}
];
var orderedCopyArray = _.sortBy(source, "a");
// Defualt ascendingconsole.log(JSON.stringify(orderedCopyArray));
// Descendingconsole.log(JSON.stringify(orderedCopyArray.reverse()));
var indexesArray = [], leng = source.length;
// Descending array orderedvar reverse = orderedCopyArray.reverse();
// Get indexfor(var i=0; i < leng; i++){
var obj1 = reverse[i];
for(var j=0; j < leng; j++){
var obj2 = source[j];
if(_.isEqual(obj1, obj2)){
indexesArray.push(j);
break;
}
}
}
console.log(indexesArray); //[2, 0, 1]
Solution 2:
Make deep copy of initial array using
array.map()
andclone
and apply sorting function overcopied
array.The
map()
method creates a new array with the results of calling a provided function on every element in this array.The
sort()
method sorts the elements of an array in place and returns the array.
Try this:
var source = [{
"a": 2,
"b": 8,
"c": 9
}, {
"a": 4,
"b": 3,
"c": 7
}, {
"a": 1,
"b": 0,
"c": 6
}];
functionclone(obj) {
if (null == obj || "object" != typeof obj) return obj;
var copy = obj.constructor();
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
}
return copy;
}
var temp = source.map(function(arr) {
returnclone(arr); //clone will make deep copy of the object
});
source[0].a = 50; //update the value from source object, it will not update `temp` array
temp.sort(function(a, b) {
return a.a - b.a; // `.a` will be the `key` to be sorted
});
snippet.log(JSON.stringify(temp));
snippet.log(JSON.stringify(source));
<scriptsrc="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Post a Comment for "How To Sort An Array In Javascript, But Save Results In Separate Array"