Sort on numericals giving improper order - javascript

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.

Related

Spinning the elements of an array clockwise in JS

I am supposed to rotate an array of integers clockwise in JS.
Here is my code for it:
function rotateArray(N, NArray)
{
//write your Logic here:
for(j=0;j<2;j++){
var temp=NArray[N-1];
for(i=0;i<N-1;i++){
NArray[i+1]=NArray[i];
}
NArray[0]=temp;
}
return NArray;
}
// INPUT [uncomment & modify if required]
var N = gets();
var NArray = new Array(N);
var temp = gets();
NArray = temp.split(' ').map(function(item) { return parseInt(item, 10);});
// OUTPUT [uncomment & modify if required]
console.log(rotateArray(N, NArray));
The code accepts an integer N which is the length of the array. The input is as follows:
4
1 2 3 4
The correct answer for this case is supposed to be
4 1 2 3
But my code returns
4 1 1 1
I cannot find where my code is going wrong. Please help me out.
All you need to do is move one item from the end of the array to the beginning. This is very simple to accomplish with .pop() (removes an item from the end of an array), then declare a new array with that element as the first:
function rotateArray(N, NArray) {
const lastItem = NArray.pop();
return [lastItem, ...NArray];
}
console.log(rotateArray(1, [1, 2, 3, 4]));
Doing anything else, like using nested loops, will make things more unnecessarily complicated (and buggy) than they need to be.
If you don't want to use spread syntax, you can use concat instead, to join the lastItem with the NArray:
function rotateArray(N, NArray) {
const lastItem = NArray.pop();
return [lastItem].concat(NArray);
}
console.log(rotateArray(1, [1, 2, 3, 4]));
If you aren't allowed to use .pop, then look up the last element of the array by accessing the array's [length - 1] property, and take all elements before the last element with .slice (which creates a sub portion of the array from two indicies - here, from indicies 0 to the next-to-last element):
function rotateArray(N, NArray) {
const lastItem = NArray[NArray.length - 1];
const firstItems = NArray.slice(0, NArray.length - 1);
return [lastItem].concat(firstItems);
}
console.log(rotateArray(1, [1, 2, 3, 4]));
function rotate(array,n){
Math.abs(n)>array.length?n=n%array.length:n;
if(n<0){
n=Math.abs(n)
return array.slice(n,array.length).concat(array.slice(0,n));
}else{
return array.slice(n-1,array.length).concat(array.slice(0,n-1));
}
}
console.log(rotate([1, 2, 3, 4, 5],-3));
The answer by #CertainPerformance is great but there's a simpler way to achieve this. Just combine pop with unshift.
let a = [1,2,3,4];
a?.length && a.unshift(a.pop());
console.log(a);
You need to check the length first so you don't end up with [undefined] if you start with an empty array.

Algorithm sorting array from closest to farthest by given number

I trying to came up algorithm in js for sorting from closest to farthest by given number, for example (number: 5.6666, array: [-1, 9, 4, 10, 11, 0]) should return [4, 9, 10, 0, 11, -1].Any idea how approach to the problem? A little gotcha actually my array is array of objects and I need sort by certain key in object. In docs said, that should use array.sort() with compare function, but I don't understand how implement this function.
The sort() function of Array can take a function:
[1,2,3].sort((a, b) => /* do something */)
Each time, you should return a value. A negative number will mean a comes before b. A positive number means b comes before a. 0 means they are equal.
If you want distance to the number, you want the absolute value, with Math.abs(). Assuming the key on the object is value, you can put it all together:
const target = 5;
const values = [{ value: -100 }, { value: 1 }, { value: 4 }, { value: 6 }, { value: 10 }];
const result = values.sort(({ value: a }, { value: b }) =>
Math.abs(target - a) - Math.abs(target - b));
console.log(result);
I used some ES6 destructuring to make it a bit cleaner by pulling the value out in the parameters.
If you wanted to just have the values remaining (instead of the objects), you can either use map() after the fact (or before).
Note, in the case of 2 numbers being equidistant from the target (in my example, 4 and 6 are both 1 away from the target), you can't guarantee which will come first. If it matters to you, you'll want to add some extra logic to hand that scenario.
Using sort, you can check each of their distances from your number.
var num = 5.666
var arr = [-1, 9, 4, 10, 11, 0]
arr.sort(function(a, b){
return Math.abs(num-a) - Math.abs(num-b);
});
console.log(arr)
Use array.sort and get the difference of each number from the input value given
var inputArray = [-1, 9, 4, 10, 11, 0],
input = 5;
var closest = inputArray.sort(function(a, b){
return Math.abs(input-a) - Math.abs(input-b);
});
console.log(closest);

Javascript tracking the differences between elements in an array?

I have the following simple array:
my_array = [1, 11, 44, 4]
I want to produce a new array consisting of the difference between these elements, so it would be:
diff_array = [10, 33, 40]
What's the best way of going about this?
You could use Array#reduce for iterating and take the absolute delta for pushing to the result array.
Basically you need array.length - 1 deltas and iteration. In this case 3. Reduce takes, if no start value is given, the first two elements and iterates the wanted length. And while it needs the last value for the delta, the last value is returned.
At the end, the returned value of reduce is discarded, becuase it is not used anymore.
1 11 44 4 values
\ / \ / \ /
10 33 40 Math.abs(delta)
var array = [1, 11, 44, 4],
result = [];
array.reduce(function (a, b) {
result.push(Math.abs(a - b));
return b;
});
console.log(result);
here is a simple solution with a plain old for loop
array = [1, 11, 44, 4]
diff = []
for(var i = 1 ; i < array.length ; i++){
diff.push(Math.abs(array[i] - array[i-1]))
}
basically you loop starting at the second element of the array ,, and subtract from from the prev and pushing to the new array .
use this function, pass it the input array, returns the required array.
function diff(array){
var out = []
for (var i = 0; i < array.length-1; i++) {
out.push(Math.abs(array[i+1]-array[i]))
}
return out;
}
Normally one can do this with .reduce() but just for fun lets get some functional.
var myArray = [1, 11, 44, 4],
diff = a => a.length > 1 ? [Math.abs(a[1]-a[0])].concat(diff(a.slice(1))) : [];
console.log(diff(myArray));
Note: The above code is just for demonstration purposes. In your daily JS life you shouldn't do things like this. Use a whatever loop you like but never use recursion in your JS code. You want to see what i mean? Feed this array.
var myArray = Array(1000000).fill().map(_ => ~~(Math.random()*100+1));
It will beautifully crash your browser's tab. Peah..!

why array.sort not work in javascript?

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() );

Merge and sort an array of numbers in numerical order - javascript

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(" ");

Categories

Resources