Array sort() gives wrong answer in JavaScript - javascript

I have intervals in an Array when I tried to use sort() to sort then it gives me wrong answer and could not able to sort it.. does someone have any idea how can I sort this.
here is what I tried
array=["1050-3000","150-250","1-49","3001-9999","251-400","401-600","601-1049","50-149"]
When I sort it:- array.sort();
It gives me this answer:-
["1-49","1050-3000","150-250","3001-9999","251-400","401-600","601-1049","50-149"]
but what I expect is:-
["1-49","50-149","150-250","251-400","401-600","601-1049","1050-3000","3001-9999"]

You have to split the string and compare the first element.
let array = ["1050-3000", "150-250", "1-49", "3001-9999", "251-400", "401-600", "601-1049", "50-149"];
array.sort((a, b) => a.split("-")[0] - b.split("-")[0]);
console.log(array);

You need to split, convert to Number and then compare
var arr = ["1-49","50-149","150-250","251-400","401-600",,"601-1049","1050-3000","3001-9999"];
arr.sort( ( a, b ) => (
al = +a.split("-")[1], //last of a, after split by -
bf = +b.split("-")[0], //first of b, after split by -
al-bf ) );

Replace dashes and sort. You don't need to split to get an array and then access the first position.
var array=["1050-3000","150-250","1-49","3001-9999","251-400","401-600","601-1049","50-149"];
array.sort((a, b) => a.replace('-', '') - b.replace('-', ''));
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

The sorting function is giving you the right output because they are strings, not numbers. You will have to write custom logic to handle this.

You have to split the dashes so as to compare the values in the array when using the array.sort(); function
Here, try this:
var array = ["1050-3000", "150-250", "1-49", "3001-9999", "251-400", "401-600", "601-1049", "50-149"];
array.sort((a,b) => a.split("-")[0] - b.split("-")[0]);
console.log(array);

Related

Sorting Array Numerical Strings from Highest to Lowest in NodeJS

I'd like to sort an array of Strings which include both Usernames & Points in the same string from Highest to Lowest, without losing the usernames, how do I do this?
I've tried:
arrayName.sort()
However, I have no idea how to make it work with strings! >w<
Here's what I'm working with:
let uwu = [
"hinata:5000",
"hiro:3000",
"karuki:6000",
"arisu: 4000"
]
Now I'd like to sort it into a new array, from Highest Points to lowest, like below! >w<
Expected Output:
["karuki:6000", "hinata:5000", "arisu:4000", "hiro:3000"]
Please do help me ! Thank you in advance !
Have a helper function that extracts the digits from the string, then call that function on both elements in the sort callback and return the difference:
const input = [
"hinata:5000",
"hiro:3000",
"karuki:6000",
"arisu: 4000"
];
const getNums = str => str.match(/\d+/)[0];
input.sort((a, b) => getNums(b) - getNums(a));
console.log(input);

Sorting string values js

I have an array that looks like this:
0123456789123456:14
0123456789123456:138
0123456789123456:0
Basically I need to sort them in order from greatest to least, but sort by the numbers after the colon. I know the sort function is kind of weird but im not sure how I would do this without breaking the id before the colon up from the value after.
Split the string get the second value and sort by the delta.
const second = s => s.split(':')[1];
var array = ['0123456789123456:14', '0123456789123456:138', '0123456789123456:0'];
array.sort((a, b) => second(b) - second(a));
console.log(array);
Assuming the structure of the items in the array is known (like described), you could sort it like this.
const yourArray = ['0123456789123456:14', '0123456789123456:138', '0123456789123456:0'];
yourArray.sort((a, b) => (b.split(':')[1] - a.split(':')[1]));
console.log(yourArray);
You can use sort() and reverse(), like this (try it in your browser console):
var arrStr = [
'0123456789123456:14',
'0123456789123456:138',
'0123456789123456:0'
];
arrStr.sort();
console.log(arrStr);
arrStr.reverse();
console.log(arrStr);
You can use below helper to sort array of strings in javascript:
data.sort((a, b) => a[key].localeCompare(b[key]))

How to sum elements of two multidimensional arrays?

I have 2 multidimensional arrays:
[[230.0], [10.0], [12.0]]
[[50.0], [60.0], [89.0]]
And am trying to sum each element together and keep the same array structure. So it should look like:
[[280.0], [70.0], [101.0]]
I tried this:
var sum = array1.map(function (num, index) {
return num + array2[index];
});
But I get this:
[23050, 1060, 1289]
Any help would be appreciated. Thanks.
The code, you use, takes only a single level, without respecting nested arrays. By taking na array with only one element without an index of the inner array and using an operator, like +, the prototype function toString is invoced and a joined string (the single element as string, without , as separator) is returned and added. The result is a string , not the result of a numerical operation with +.
You could take a recursive approach and check if the value is an array, then call the function again with the nested element.
function sum(a, b) {
return a.map((v, i) => Array.isArray(v) ? sum(v, b[i]) : v + b[i]);
}
console.log(sum([[230], [10], [12]], [[50], [60], [89]]))
Make it like this
var sum = array1.map(function (num, index) {
return parseInt(num) + parseInt(array2[index]);
});
You should have to make parseInt or parseFloat so it can convert string with them
STEPS
Iterate through every number in the array (array length).
Sum the objects of the same index in both of the arrays.
Push the sum into another array for the result. Use parseFloat if the input is string.
(Optional) use .toFixed(1) to set decimal place to have 1 digit.
const arr1 = [[230.0], [10.0], [12.0]]
const arr2 = [[50.0], [60.0], [89.0]]
let sum = []
for (let i = 0; i < arr1.length; i++){ // Assume arr1 and arr2 have the same size
let eachSum = parseFloat(arr1[i]) + parseFloat(arr2[i])
sum.push([eachSum.toFixed(1)])
}
console.log(sum)
You are trying to add two arrays structures inside the map function.
so one solution so you can see what is happening is this...
array1.map((a,i) => a[0] + array2[i][0])
screenshot from the console...
Inside map fn you should:
return parseInt(num) + parseInt(array2[index]);
This is happening because when you are trying to add them, these variable are arrays and not integers. So they are evaluated as strings and concatenated.

Need to fetch the numbers from an array

I have got an array of the form:
['32 68', '56 78', '77 99']
I want to o/p another array which will contain the sum of each element in the index using JavaScript (NodeJS). Something like,
['100', '134', '176']
I tried to use .split("") but the double integer number again gets separated as separate digits. Is there any other way to solve this? Please not that, the i/p can be single digit number or double digit.
You'll want to get each item, split on a space (if exists) then add up the corresponding split. Something like this:
var origValues = ['32 68', '56 78', '77 99', '7'];
var addedValues = origValues.map(function(value) {
return value.split(' ')
.map(function(sArray) {
return parseInt(sArray);
})
.reduce(function(a, b) {
return a + b;
});
});
document.write(JSON.stringify(addedValues));
Note that this above example handles the case where you have a single digit inside your array value as well.
To provide some explanation as to what is happening...
You start off taking your original array and you are mapping a function on to each value which is what is passed into that function.
Inside that function, I am splitting the value by a space which will give me an array of (possibly) two values.
I then apply the map function again onto the array and parse each value in the array to an integer.
Last, I reduce the integer array with a summation function. Reduce applies an accumulator function to each item in the array from left to right so you will add up all your values. This result is returned all the way back up so you get your new array with your answers.
Kind of what it looks like in "drawing" form:
Start: origValues = ['32 68', '56 78', '77 99', '7']
Apply map (this will track one value): value = '32 68'
Apply the split: ['32', '68']
Map the parse integer function (I'm going to track both values): [32, 68]
Reduce: 32 + 68 = 100
I don't have time for an explanation (sorry) but, split + reduce will do it.
var arr = ['32 68', '56 78', '77 99'];
var sumArray = arr.map(function (s) {
return s.split(' ').reduce(function (a, b) {
return parseInt(a, 10) + parseInt(b);
});
});
document.write(JSON.stringify(sumArray));
You don't actually need map or anything. For each string we can .split, Numberify, and add.
secondArray[value] =
Number((firstArray[value].split(" "))[0]) +
Number((firstArray[value].split(" "))[1]);
Modifying this and turning this into a for loop, we get:
var arr2 = [];
for(var i = 0; i < arr.length; i ++){
arr2.push(
Number((arr[i].split(" "))[0]) +
Number((arr[i].split(" "))[1]));
}
arr = arr2;

Sorting an array in javascript: [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Sort mixed alpha/numeric array
I'm trying to sort an array which contains elements in the form of xxx1, xxx2, xxx3. The Array.sort() method works fine until xxx9 and if there is an element by name xxx10 or xxx11, it fails. The order comes as xxx1, xxx10, xxx11, xxx2 and so on. Please let me know how to fix this.
You are seeing the results of natural string sorting. If string sort is not what you want, you should be using your own comparator.
Do something like:
arrayToBeSorted.sort(function(first,second)
{
/* some code that compares 'first' with 'second' and returns <0, ==0, >0*/
});
At the moment your array is being sorted alphabetically which is why you are getting those results. You need to provide your own comparator function to implement a numerical sort.
Try
var arr = ["xxx1","xxx10","xxx2","xxx20","xxx3","xxx30"];
var sortedArr = arr.sort( function( a, b ) {
// remove first 3 characters so remaining string will parse
a = parseInt( a.substr( 3 ) );
b = parseInt( b.substr( 3 ) );
return a - b;
});
console.log( sortedArr ); // => ["xxx1", "xxx2", "xxx3", "xxx10", "xxx20", "xxx30"]
You can implement custom sorting condition in callback to pass into Array.sort():
​var arr = [],
re = /^\D*(\d+)$/;
for(var i = 20; i-- > 0;) {
arr.push('xxx' + i);
}
function comparator(a, b) {
var numA = a.match(re)[1],
numB = b.match(re)[1];
return numA - numB;
}
arr.sort(comparator);
console.log(arr);
​
http://jsfiddle.net/f0t0n/qz62J/

Categories