This question already has answers here :
In JS, the array name only stores the reference to the original array. And sort mutates (changes) the array. You are not making a copy of the array with
const orderBirth = inventors.sort((a, b) => a.year > b.year ? 1 : -1);
Rather, you are storing the reference to the array sorted by year.
When you sort again with different function, the main array changes. And the orderBirth is still pointing to it. So that changes as well.
edit : As Scorpioo590 has said, .slice() method will duplicate the array.
const orderBirth = inventors.slice().sort((a, b) => a.year > b.year ? 1 : -1);
So what you assumed the '=' operator did is correctly achieved in this way.
Using JavaScript's sort Method for Sorting Arrays of Strings , First of, the ECMAScript standard does not specify a particular sorting algorithm, it all are numbers, then sorted sequentially, in ascending order by default. We' ll start by creating utility functions that helps get the unicode values tools in the React front-end JavaScript library that run custom functions … Why does it need to run for only the first n-1 elements, rather than for all n elements? Give the best-case and worst-case running times of selection sort in Ɵ-notation.
Sort mutates the original array. so when you use sort sequentially eventually you're changing the same array again and again.
let arr = [1,2,3,5,6,64,76,52]
arr.sort((a,b)=> a-b)
console.log(arr)
The 10 Most Common Mistakes JavaScript Developers Make, At first blush, JavaScript may seem quite simple. As a result, the anonymous function being passed to setTimeout() is being defined in the If you run the above code and monitor memory usage, you'll find that you've got a massive Yes, I know this is the right way sort an array of numbers - but for developers who are� Because of this, the sort() method will produce an incorrect result when sorting numbers. You can fix this by providing a "compare function" (See "Parameter Values" below). Note: This method changes the original array.
sort
mutates the original array and returns the sorted array. So, they are all pointing to the same array in memory. Both of these will return true
:
console.log(inventors === orderBirth)
console.log(oldest === orderBirth)
const inventors=[{first:'Albert',last:'Einstein',year:1879,passed:1955},{first:'Isaac',last:'Newton',year:1643,passed:1727},{first:'Galileo',last:'Galilei',year:1564,passed:1642},{first:'Marie',last:'Curie',year:1867,passed:1934},{first:'Johannes',last:'Kepler',year:1571,passed:1630},{first:'Nicolaus',last:'Copernicus',year:1473,passed:1543},{first:'Max',last:'Planck',year:1858,passed:1947},{first:'Katherine',last:'Blodgett',year:1898,passed:1979},{first:'Ada',last:'Lovelace',year:1815,passed:1852},{first:'Sarah E.',last:'Goode',year:1855,passed:1905},{first:'Lise',last:'Meitner',year:1878,passed:1968},{first:'Hanna',last:'Hammarström',year:1829,passed:1909}]
const orderBirth = inventors.sort((a, b) => a.year > b.year ? 1 : -1);
const oldest = inventors.sort((a, b) => {
const lastInventor = a.passed - a.year;
const nextInventor = b.passed - b.year;
return lastInventor > nextInventor ? -1 : 1;
});
console.log(inventors === orderBirth)
console.log(oldest === orderBirth)
Analysis of selection sort (article), Remember that indexOfMinimum and swap are functions: when either is If the subarray is the whole array (as it is on the first step), the loop body runs What if the number of integers in the sequence is odd, so that you cannot pair them all up ? do we have to draw the lines manually or using the displayArray() function? Example of Quick Sort in JavaScript This is a function to take care of the Quick Sort in JavaScript. In this, we will pass the complete list of the array as input and will get the sorted array as output.
As you mentioned the sort functions alters the original array.
With
const orderBirth = inventors.sort(...)
you get a reference to the array. Meaning both variables actually point to the same place in memory. Thus when changing the original array you also change the new variable.
You would need to create a copy of the original array to preserve the result of the sorting.
const orderBirth = inventors.sort(...).slice();
should do the trick.
Getting things sorted in V8, Starting with V8 v7.0 / Chrome 70, Array.prototype.sort is stable. A comparison function that does not follow this pattern is inconsistent and can have Accessors are the first case where the resulting sort order is implementation- defined: Note that Timsort only merges consecutive runs, this is needed to� The code for insertion sort has two indices, i and j.i tracks our outer loop and represents the current element we are sorting.It starts at 1 instead of 0 because when we only have one element in
JavaScript Array sort: Sorting an Array More Effectively, This tutorial shows you how to use the JavaScript array sort method to sort arrays sorts the array elements in ascending order with the smallest value first and The sort() method will use the compare function to determine the orders of elements. Output: [ 0, 1, 2, 3, 10, 20, 30 ]. Or you can define the comparison function� What is coming to every javascript function, i.e. the arguments object, is not exactly an array. It doesn't have shift method, so I simply create a real array and add all the sent functions there. After that the first method of the newly array is fetched and called. In its callback the run method is fired again.
Deeply Understanding JavaScript Async and Await with Examples , A callback is nothing special but a function that is executed at some Looping over multiple promises in a sequence is challenging and Needless to say, don't use async/await or .sort function. foo() will return a rejected promise if the error is uncaught. It is like the first example above with just await . JavaScript Function: Exercise-24 with Solution. Write a JavaScript function to apply Bubble Sort algorithm. Note: According to wikipedia "Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order".
Array.prototype.slice(), The slice() method returns a shallow copy of a portion of an array into a new array object selected expected output: Array ["camel", "duck"]. 8 If start is greater than the index range of the sequence, an empty array is returned. end If a new element is added to either array, the other array is not affected. “Why does the (D)First (or (D)Last) function not show the value I expected it to show?” The first question is crucial to understand the core issues here, so let’s focus on that one first. The Order of Query Results. Why are your results not sorted in the order you expected? Let go of your concept of sequential records.
Comments please have alook here, too, regarding only two values as return value for sorting: stackoverflow.com/q/24080785 I don't think this is a duplicate question, they deal with the same issue but I understood that the sort function mutates the original array (and mentioned it my question). Where I became unstuck was in terms of the variable pointing to the same in-memory array and also the fact that I was never actually re-running the function. Maybe add that this happens even when assigning to a variable. Thanks for the comment but why cant we continue to mutate the array with a different sort? So initially I sort by birth and the array is mutated. Then I sort by age and the array is mutated. Why would it stop there and not allow me to re-mutate by running the sort by birth function again? I think Jack may have given me the clue - I'm not re-running the function, I'm just re-logging the variable! Thanks for your help both.