I originally had the following callback passed as a parameter to the javascript array sort() function:
function sortNumber(a,b) {
return a-b;
}
However this doesn't work when my array contains positive and negative decimal numbers (i.e. -107.578, 97.453 etc.) How would I modify this to sort properly?
I don't see any problems with that function. Here's my test code:
var nums = [10, 5, 40, 25, -3412,4212, -107.578, 97.453];
function sortNumber(a,b){
return a - b;
}
alert( nums.sort(sortNumber) );
Can you show some more of your code? It might be a problem with the array.
Related
Is there a way to get prime numbers in one line
I was given a task to get the largest prime number in an array in one line is that even possible?!
Given an array of numbers. Create a function which returns the largest prime number. (NOTE*,
it should be written only 1 line of code). (2)
let arr1 = [1,5,7,6,9,10,13,11,12]
function largestPrime(arr) {
// write your code here... }
}
Referring the great answer of #Sergio to the question: Number prime test in JavaScript. You can filter the prime numbers in the array then get the largest one by using the Math.max function.
let arr1 = [1,5,7,6,9,10,13,11,12]
function largestPrime(arr) {
return Math.max(...arr.filter((n) => { return ![...Array(n).keys()].slice(2).map(i => !(n%i)).includes(true) && ![0,1].includes(n) }));
}
console.log(largestPrime(arr1));
I have array of object .I want if i add object in array it should add in sorted way .I used array to sort .but it not sort my array . here is my code
https://jsfiddle.net/8oczc5x5/
var arr = [{
elem: {
text: function() {
return "aa";
}
}
}, {
elem: {
text: function() {
return "yy";
}
}
}];
var obj = {
elem: {
text: function() {
return "bb";
}
}
}
arr.push(obj);
arr.sort()
console.log(arr[1].elem.text())
Expected Out put
"bb"
Actual output
"yy"
..why ? I used sort it should sort my array ?
sort only really works "out-of-the-box" when sorting character data alphabetically. And why would you expect it to call your functions and compare them? That's really dangerous and complicated. However, you can perform your own special sort by passing it a function.
Taken from the docs (compareFunction is the function you're passing in):
If compareFunction is supplied, the array elements are sorted according to the return value of the compare function. If a and b are two elements being compared, then:
If compareFunction(a, b) is less than 0, sort a to a lower index than b, i.e. a comes first.
If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
If compareFunction(a, b) is greater than 0, sort b to a lower index than a.
compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned then the sort order is undefined.
arr.sort(function(a, b) {
// localeCompare does a string comparison that returns -1, 0, or 1
return a.elem.text().localeCompare(b.elem.text());
});
function sortNumber(num1,num2) {return num1 - num2;} var numbs = [5, 17, 29, 48, 4, 21];
var sortnumb = numbs.sort(sortNumber);
alert(sortnumb)
You have to specify how to sort
arr.sort( (a,b) => a.elem.text().localeCompare(b.elem.text() );
I am trying to merge and sort 2 arrays in numerical order.
function merge_arrays(a, b) {
console.log( (a.concat(b)).sort().join(" ") );
}
This works fine with single digits in an array, but it doesn't sort numbers with double digits properly.
e.g.:
a: [2, 3, 7, 8, 8,]
b: [7, 8, 13]
will output as: 13 2 3 7 7 8 8 8
Am I missing something?
Quoting from MDN:
The default sort order is lexicographic (not numeric).
Try this instead:
function merge_arrays(a, b) {
console.log( (a.concat(b)).sort(function(a, b) { return a - b; }).join(" ") );
}
http://www.w3schools.com/jsref/jsref_sort.asp
See that section
Note: When numbers are sorted alphabetically, "40" comes before "5".
To perform a numeric sort, you must pass a function as an argument when calling the sort method.
The function specifies whether the numbers should be sorted ascending or descending.
Meaning This
function numOrdA(a, b){ return (a-b); }
and your code :
a.concat(b)).sort(numOrdA).join(" ")
Try this:
c = a.concat(b)
c == [2,3,7,8,8,7,8,13]
c.sort() == [13,2,3,7,7,8,8,8]
This is because, when not provided with a comparison function, sort automatically converts the elements of the list it is sorting to strings. In string land "13" < "2".
Check out the sort documentation.
So what you probably want is something like this:
function compare_number(a,b) {
return a - b;
}
a.concat(b).sort(compare_number);
And to fully answer your question:
a.concat(b).sort(compare_int).join(" ");
var t = [-12, 57, 22, 12, -120, -3];
t.map(Math.abs).reduce(function(current, previousResult) {
return Math.min(current, previousResult);
}); // returns 3
t.map(Math.abs).reduce(Math.min); // returns NaN
I don't understand why the second form doesn't work. Any explanations are welcomed.
EDIT: Technical context: Chrome and Firefox JavaScript engine. See ES5 reduce http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.21
Math.min accepts multiple arguments. This is exactly the same reason this doesn't work for parseInt or other functions like that. you need to bind the parameters yourself.
reduce feeds the values like index and array to Math.min
We can confirm this if we follow the following steps:
First, we proxy Math.min:
var oldMath = Math.min;
Math.min = function (){
console.log(arguments)
return oldMath.apply(Math, arguments);
}
Then we run the second version:
[-12, 57, 22, 12, -120, -3].reduce(Math.min);
Which logs:
[-12, 57, 1, Array[6]]
Since Array[6] is not a number, the result is NaN
Here is a very similar example from MDN:
["1", "2", "3"].map(parseInt);
While one could expect [1, 2, 3]
The actual result is [1, NaN, NaN]
parseInt is often used with one argument, but takes two. The second being the radix
To the callback function, Array.prototype.map passes 3 arguments: the element, the index, the array
The third argument is ignored by parseInt, but not the second one, hence the possible confusion.
reduce's callback is called passing four arguments: previousValue, currentValue, index and array. And because Math.min is a variadic function, your code:
t.map(Math.abs).reduce(Math.min); // returns NaN
is equivalent to:
t.map(Math.abs).reduce(function(current, previousResult, index, array) {
return Math.min(current, previousResult, index, array);
});
That's why the result is NaN: the last parameter, array, is not a number.
You can also solve this kind of issue with a high-ordered function like this one:
function binary (fn) {
return function (a, b) {
return fn.call(this, a, b);
}
}
And then:
t.map(Math.abs).reduce(binary(Math.min));
will works.
Here is my code snippet
$(document).ready(function(){
var mylist = [ "20","3","100","50"];
mylist = mylist.sort();
$("#mydiv").html(mylist.join(""));
});
Its printing on my div like below
100
20
3
50
But giving proper order if I am giving data like "twenty","three","hundread","fifty".
fifty
hundread
three
twenty
Please help,what I am missing??
Thanks.
The default compare mathod use alphabetic order. If you want to sort numbers use this:
arr.sort(function(a,b) {
return a - b;
});
Array.sort() sorts values in alphabetical order by default.
The method can also be used with an optional parameter: a comparaison function
To sort numerical values, use:
var numbers = [4, 2, 5, 10, 3];
numbers.sort(function(a, b) {
return a - b;
});
// numbers -> [2, 3, 4, 5, 10]
Try this:
var sortnumerically = function(a,b){
if (a<b) return -1;
else if (a>b) return 1;
else= return 0;
}
var mylist = [ 20,3,100,50];
mylist = mylist.sort(sortnumerically);
$("#mydiv").html(mylist.join(","));
okay, to explain the sortnumerically comparator function. Simply put it accepts two inputs a,b : elements presumably from the array. If ab returns 1 (that's what a comparator is supposed to do).
http://jsfiddle.net/Lmzua/1/
Remove quotes from the array values and use below extra function to get ascending order
Mylist = Mylist.sort (function (a, b){return a-b});
You defined your numbers as string literals thus js sorts them as strings. You need to define then as number literals: [ 20, 3, 100, 50] for the sort to work as required.