Page 112 - JavaScript
P. 112
Date Sort (descending)
var dates = [
new Date(2007, 11, 10),
new Date(2014, 2, 21),
new Date(2009, 6, 11),
new Date(2016, 7, 23)
];
dates.sort(function(a, b) {
if (a > b) return -1;
if (a < b) return 1;
return 0;
});
// the date objects can also sort by its difference
// the same way that numbers array is sorting
dates.sort(function(a, b) {
return b-a;
});
Results in:
[
"Tue Aug 23 2016 00:00:00 GMT-0600 (MDT)",
"Fri Mar 21 2014 00:00:00 GMT-0600 (MDT)",
"Sat Jul 11 2009 00:00:00 GMT-0600 (MDT)",
"Mon Dec 10 2007 00:00:00 GMT-0700 (MST)"
]
Shallow cloning an array
Sometimes, you need to work with an array while ensuring you don't modify the original. Instead of
a clone method, arrays have a slice method that lets you perform a shallow copy of any part of an
array. Keep in mind that this only clones the first level. This works well with primitive types, like
numbers and strings, but not objects.
To shallow-clone an array (i.e. have a new array instance but with the same elements), you can
use the following one-liner:
var clone = arrayToClone.slice();
This calls the built-in JavaScript Array.prototype.slice method. If you pass arguments to slice, you
can get more complicated behaviors that create shallow clones of only part of an array, but for our
purposes just calling slice() will create a shallow copy of the entire array.
All method used to convert array like objects to array are applicable to clone an array:
6
arrayToClone = [1, 2, 3, 4, 5];
clone1 = Array.from(arrayToClone);
clone2 = Array.of(...arrayToClone);
https://riptutorial.com/ 69

