sort() does not work - javascript

I use sort() to sort my table but I do not understand why it does not work. you have an idea ?
var tab = [5, 15, 17, 3, 8, 11, 28, 6, 55, 7];
tab = tab.sort();
for (var i = 0; i < tab.length; i++) {
$("p").append(" ", tab[i]);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p></p>
https://jsfiddle.net/1423tLwd/

By default the sort method will sort the array that it has been called on alphabetically.
To get around this you need to pass sort a callback function that will sort the elements by their numerical value.
To achieve this you need to do the following:
function sortNumber(a, b) {
return a - b;
}
let tab = [5, 15, 17, 3, 8, 11, 28, 6, 55, 7];
let sortedTab = tab.sort(sortNumber);
console.log(sortedTab);

As Explained in MDN web docs:
The default sort order is according to string Unicode code points.
That is, you should give sort the function that is to compare elements of the array, otherwise, your array will be sorted according to string Unicode code points.
This should work (sort in ascending order):
function compareFunction(a, b) {
return a - b;
}
// sort tab array using compareFunction to compare elements
tab.sort(compareFunction);

Related

How to cycle through an array of values to optimize number of calls to a function?

I have an array of rows from a Google Spreadsheet interspersed with numbers between the bounds of 1 and 800:
var rowPositions = [1,3,4,5,9,10,11,12...795,799,800]
And, for efficiency's sake, I need to make an API call to the function deleteRows, which accepts two parameters:
deleteRows(positionOfFirstRow, howManyRowsShouldBeDeletedStartingFromFirstRow)
Google Documentation for deleteRows.
How can I create a function in Javascript that calls deleteRows a minimal number of times for a given array? IE, using the aforementioned array as an example, the function calls deleteRows to remove the row at position 1, then calls it again to delete 3,4,5, then again to delete 10,11,12, etc...?
In other words, how can I transform that rowPositions array into a two-dimensional one, ex.:
var 2DrowPositions = [[1,1],[3,2],[5,1],[9,4]]
which I can then use to call the deleteRows function once per provided coordinate.
If you are given an array of items to delete like [1, 3, 4, 5, 7, 8, 9, 15, 18, 19, 20, 23] you can step through that array and look for consecutive numbers. Keep track of how many consecutive numbers you see and when you hit a non-consecutive number, save the old one and start again.
Here's one way to do that, which is reasonably easy to read:
let del = [1, 3, 4, 5, 7, 8, 9, 15, 18, 19, 20, 23]
let res = []
let curr = {start: del[0], count: 0}
del.forEach((item, i, arr) => {
if (i === 0 || arr[i] === 1 + arr[i-1]) curr.count++
else {
res.push(curr)
curr = {start: arr[i], count:1}
}
})
res.push(curr)
console.log(res)
This will return an array of objects of the form {start, count} which you can use in your function with something like:
res.forEach(r => deleteRows(r.start, r.count))

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

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

Splice items from array considering indexes from another array

I have an array input and another array indexes. I want to remove item from array input whose index is provided in indexes array.
I have tried it using array.splice in for loop but as item is being removed in each iteration, indexes of other items are being changed.
JavaScript:
var array = [10, 11, 12, 13, 14, 15];
var indexes = [0, 1, 2, 3, 4, 5];
indexes.forEach(function(item) {
array.splice(item, 1);
});
console.log(array);
You can utilize Array.prototype.filter and do the following:
var array = [10, 11, 12, 13, 14, 15];
var indexes = [0, 1, 2, 3, 4, 5];
array = array.filter(function(x, i) {
return indexes.indexOf(i) === -1;
});
console.log(array);
Here you are using forEach loop which give you the item as first argument and the index on second one, so as per my understanding what you want to do can achieve by this, try this hope this solve your problem :)
indexes.forEach(function(item, index) {
array.splice(index, 1);
});
Sort the indexes array from high to low, then spice will only change the index of the numbers you have already removed

Finding the lowest number in an array using split('') and reverse();

I am trying to find the min value of an array, and am trying to do it by sorting the array, and then reversing the array, and then calling the very first index of the array.
Unfortunately with what I have been trying, I keep getting 9. (don't know why) Can anybody take a quick look at what I have been doing and bail me out here? (i'm using js)
var minny = [4, 3, 5, 2, 6, 3, 4, 5, 2, 3, 4, 6, 7, 8, 9, 9, 1, 11, 25];
var smallest = function (minny){
minny = minny.sort('');
var sorted = minny + " ";
sorted = minny.reverse('').join('');
return sorted[0];
}
console.log(smallest(minny))
By default the sort method sorts elements alphabetically(11 comes before 9) and therefore you need to add a compare function as a param.
var smallest = function (minny) {
minny = minny.sort(function(a, b) { return a - b; });
return minny[0];
}
console.log(smallest(minny))
JSFIDDLE.
Based on your code, you could just do
return minny.sort()[0];
So, your full code example becomes
var minny = [4, 3, 5, 2, 6, 3, 4, 5, 2, 3, 4, 6, 7, 8, 9, 9, 1, 11, 25];
var smallest = function (minny){
return minny.sort()[0];
}
console.log(smallest(minny))
You're calling minny.sort('') which is using the default natural sort, so 11 and 25 end up near the beginning because of the 1 and 2.
What you have to do is call sort with a function that compares numbers, such as:
minny.sort(function(a,b) { return b-a; });
This will sort minny the way you want it.
There is no need to even call reverse and join afterwards, just return the first item. "return sorted[0]" is fine but will fail if there are no items, so you might just want to call "return sorted.shift()" instead. This will return the first item too, but won't fail if the array is empty.
PS. your call to minny.reverse also has an empty string as a parameter. That's not needed, reverse takes no parameters.
sort() sorts alphabetically by string representation, so in your case it would result in 1, 11, 2, 2, 25, .... You have to provide a comparison function for correct integer sorting, although in your specific case it doesn't really make a difference.
var smallest = function (minny){
minny = minny.sort(function(a, b){return a-b});
return minny[0];
}
See jsfiddle
Using sort is fairly short code to write, and it will return the correct number if you use minny.sort(function(a,b){return a-b})[0].
If you have a large unordered array you are running the comparison many times and you are sorting the array, which is not usually what you want to do to an array.
It may be better to just iterate the members and compare each just once to the lowest fond so far.
var minny= [4, 3, 5, 2, 6, 3, 4, 5, 2, 3, 4, 6, 7, 8, 9, 9, 1, 11, 25];
var smallest= function(minny){
var min= Infinity;
minny.forEach(function(next){
if(next<min) min= next;
});
return min;
}
Or use Math.min, if this is code golf:
Math.min.apply(Array,minny);

Categories

Resources