Sorting array with sort function [duplicate] - javascript

This question already has answers here:
How does Javascript's sort() work?
(8 answers)
How does sort function work in JavaScript, along with compare function
(7 answers)
How does JavaScript's sort (compareFunction) work? [duplicate]
(3 answers)
Closed 1 year ago.
I got question today, that I couldn't answer. I would appreciate if you could just explain it to me. Why my array doesn't output [1, 2, 3, 4, 5] but only [2, 3, 4, 5]?
This is the code:
let numbers = [1, 2, 3, 4, 5]
let order = numbers.sort((a, b) => {
console.log(a);
});
But when I use this code, it works perfectly fine
let numbers = [1, 2, 3, 4, 5]
let order = numbers.sort((a, b) => {
return a;
})
console.log(order);

It doesn't output [2, 3, 4, 5] it outputs 2, 3, 4 and 5 each in a separate step of the iteration. If you also log order you'll see that the array still contains [1, 2, 3, 4, 5]. The comparator function receives two elements of the array that it compares to each other. That way it knows in which order those elements should be. If you only log a and not b, you'll wont see all the information that is passed to the comparator. If you log both a and b, you'll see that also 1 is passed, to parameter b.
let numbers = [1, 2, 3, 4, 5]
let order = numbers.sort((a, b) => {
console.log('Comparing', a, b);
});
console.log('Final result', order);
Keep in mind that the comparator function should return either a positive number when a is greater than b, a negative number when a is less than b and 0 when both elements are equal to each other. The above comparator function doesn't return any value at all, so it might not do what you expect it to do.
(Also your snippet that "works perfectly fine" doesn't follow that contract. It returns a positive number for each element, so it is basically saying that every element is greater than every other element.)

The sort() method sorts the elements of an array in place and returns the sorted array.
[1, 2, 3, 4, 5].sort((a, b) => {
console.log({a, b}); // a is secondItem, b is firstItem of an array
return -1; // return -ve value for DESC and truthy value for ASC order
});
Output will be
{a: 2, b: 1}
{a: 3, b: 2}
{a: 4, b: 3}
{a: 5, b: 4}
sort output: [5, 4, 3, 2, 1]

Related

sorting an array according to the order of another array - pair inputs [duplicate]

This question already has answers here:
sort 2 array with the values of one of them in javascript
(4 answers)
Closed 2 years ago.
so I have two arrays - arrOne = [10, 2, 3, 14, 1] and arrTwo = [1, 2, 3, 5, 4];
I want sort the arrTwo and use the same indexing changes on arrOne, ie arrTwo = [1, 2, 3, 4, 5], arrOne [10, 2, 3, 1, 14].
I've been trying to implement it with merge sort, but it does not work. The recursion obstructs me from doing what I intended.
Important to note, I am getting the data as two integers at a time and push them into separate arrays, using the previous arrays that would mean -
input 10 ,1
input 2, 2
input 3, 3
input 14, 5
input 1, 4
Perhaps a different data structure could be used, but I am not aware of it.
I have put go as a tag since I would like to solve it both languages.
Create a 2d array which holds value of 2 arrays and extract 2 arrays after sorting.
let arrOne = [10, 2, 3, 14, 1],
arrTwo = [1, 2, 3, 5, 4];
arrOne
// create 2d array which contains both array values
.map((v, i) => [v, arrTwo[i]])
// sort the combined array based on first array element
.sort(([a], [b]) => a - b)
// update the main arrays
.forEach(([v1, v2], i) => {
arrOne[i] = v1;
arrTwo[i] = v2;
})
console.log(arrOne, arrTwo)
To solve this I would not use two arrays.
I would push an object to a single array. Making it much more structured keeping the data “together”
const data = [{
one: 10,
two: 1
},
{
one: 2,
two: 2
},
{
one: 3,
two: 3
},
{
one: 14,
two: 5
},
{
one: 1,
two: 4
}
To add another input:
data.push({
one: 200,
two: 6
})
Then sort by key “two”
data.sort((a, b) => {
return a.two-b.two
})
Just note that the sort will mutate the array but you can copy if this is an issue. Guessing sorting the original array is not a problem for your use case anyway.

Why spread operator turn my array into numbers

i have
a = [[1,2,3],[4,5,6]]
How come when i write
console.log(...a.shift())
it gives me 1 2 3
but not 1,2,3 nor [1, 2, 3]
can anyone explain me the mechanism behind this?
a.shift() returns the first element of the array, which is [1, 2, 3]. So your code is equivalent to:
console.log(...[1, 2, 3])
The spread syntax causes each element of the array to become a separate argument, so this is equivalent to
console.log(1, 2, 3)
which prints each number separately on the console.
To get [1, 2, 3] you shouldn't use ..., just write
console.log(a.shift())
To get 1,2,3 use
console.log(a.shift().join(','))
console.log(...a.shift())
is run in given order:
a.shift() returns [1, 2, 3] => console.log(...[1, 2, 3])
...[1, 2, 3] is evaluated into 1 2 3 and passed to console.log as 3 different arguments => console.log(1, 2, 3)
Which has out of 1 2 3

Calling Array.prototype.map with Math.max returns array of NaN [duplicate]

This question already has answers here:
Why does parseInt yield NaN with Array#map?
(8 answers)
Closed 4 years ago.
Why does [1, 2, 3].map((x) => Math.max(x)) return [1, 2, 3]
yet [1, 2, 3].map(Math.max) returns [NaN, NaN, NaN] ?
I would have thought since [1, 2, 3].map(Number) returns [1, 2, 3], the same would true for using Math.max in the same way.
Especially since Math.max(3) == Number(3).
It's because map invokes the callback with three arguments:
The current array element.
The index of the current element.
The array map was called on.
So [1, 2, 3].map(Math.max) is not equivalent to [1, 2, 3].map((x) => Math.max(x)), but to [1, 2, 3].map((x, i, arr) => Math.max(x, i, arr)).
And Math.max(1, 0, [1, 2, 3]) is NaN because the [1, 2, 3] array becomes "1,2,3" when stringified, which becomes NaN when converted to a number.
You can use spread operator:Math.max(...[1,2,3])

How will I sort a list using javascript?

I want to sort a list on my site using JavaScript. I've search on w3c but it seems that I need to make a button for that. I want to sort a list automatically. Please help me.
Use .sort(<compare function>)
From MDN:
The sort() method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
Examples
For Ascending
var arr = [1, 6, 3, 8, 10, 3, 4, -1]; //unsorted array
arr.sort(function (a, b) {
return a - b;
});
result: -1,1,3,3,4,6,8,10
or
var arr = [1, 6, 3, 8, 10, 3, 4, -1]; //unsorted array
arr.sort(sortAscending);
function sortAscending(a, b) {
return a - b;
}
result: -1,1,3,3,4,6,8,10
For Descending
var arr = [1, 6, 3, 8, 10, 3, 4, -1]; //unsorted array
arr.sort(sortDescending);
function sortDescending(a, b) {
return b - a;
}
result: 10,8,6,4,3,3,1,-1
NOTE The compare function being passed may not suit your needs so you need to be more specific about what you're sorting for an answer that's more specific to your problem

what does max() function do in javascript if array has several equally large numbers

If we get something like
array=[5,5,5,5,3,2];
return Math.max.Apply(Math,array);
How do I get it to return the numbers from first to last if such a case occurs.
To answer the question in the title:
what does max() function do in javascript if array has several equally
large numbers
The answer is, nothing. Math.max() doesn't act on arrays.
You can pass an array by spreading the items as arguments to max():
Math.max(...[1,2,3]) // 3
Or as you've seen, with apply():
Math.max.apply(Math, [1,2,3]) // 3
If the question is more:
What does Math.max() do when more than one of the same maximum number is given?
The answer is, it returns that number:
const a = [5, 5, 5, 5, 3, 2]
const max = Math.max(...a)
console.log(max) // 5
This question is confusing:
How do I get it to return the numbers from first to last if such a case occurs.
You want it to return a sorted array? From [5, 5, 5, 5, 3, 2] to [2, 3, 5, 5, 5, 5]?
a.sort() // [2, 3, 5, 5, 5, 5]
You want dupes removed? From [5, 5, 5, 5, 3, 2] to [2, 3, 5]?
Array.from(new Set(a)) // [2, 3, 5]
Could you clarify your question?
The best way to do this is the following:
var a = [5,5,5,5,3,2];
var largest = Math.max.apply(null,a)
var filtered = a.filter(function(item) {
item === largest
});
Where filtered will have contain all the largest elements.
In #Clarkie's example, he's calling Math.max more frequently than needed.
In both Dan and Clarkie's example they're capitalizing Apply which is incorrect, the correct function to call is Math.max.apply and Math need not be passed in as the first argument.
See the following for a working example:
https://jsfiddle.net/fx5ut2mm/
Modifying #Clarkie's very nice idea. We can boil it down to...
var a = [5,5,5,5,3,2],
m = Math.max(...a),
f = a.filter(e => e == m);
document.write("<pre>" + JSON.stringify(f) + "</pre>");

Categories

Resources