Sorting string values js - javascript

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

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

remove duplicates from array in moment js

i have
let array = [moment('2019-01-17'),moment('2019-01-19'),moment('2019-01-19'),moment('2019-01-21')];
i need to remove duplicates
so i written filter but it is not working correctly
array= array.filter((v,i) => !moment(array.indexOf(v)).isSame(moment(i)))
working live plunker code inside index.html
You were on the right track, but details were a bit off. Please try this:
const comparisonValues = array.map(v => v.valueOf());
array = array.filter((v,i) => comparisonValues.indexOf(v.valueOf()) == i);
Explanation:
array.filter((value, index, self) => self.indexOf(value) == index) is an useful pattern for finding unique values in an array
The intuition behind the pattern is to "pick only first instances of a value in an array"
It only works for values that can be directly compared - indexOf uses strict equality check internally (===)
momentValue.valueOf() will return an useful value for this comparison, namely number of milliseconds since the Unix Epoch
Our solution uses a helper array that consists of the millisecond values from valueOf and in filter, makes comparisons using valueOf() of the current value in iteration
Another way, if you want to use isSame, could be like this:
array = array.filter((v, i) => {
return array.findIndex(candidate => v.isSame(candidate)) == i
});
You can achieve the same result and faster with just a single Array.reduce and once you got the items grouped just get them via Object.values. This would be faster than for each items searching the entire array every time. For small arrays it would not matter but for larger it would be quite noticeable.
Here is the concise version:
let data = [moment('2019-01-17'), moment('2019-01-19'), moment('2019-01-19'), moment('2019-01-19'), moment('2019-01-19'), moment('2019-01-21')];
const result = data.reduce((a, c) => (a[c.format()] = c, a), {})
console.log(Object.values(result))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
And here the detailed one:
let data = [moment('2019-01-17'), moment('2019-01-19'), moment('2019-01-19'), moment('2019-01-19'), moment('2019-01-19'), moment('2019-01-21')];
const result = data.reduce((accumulator, current) => {
accumulator[current.format()] = current
return accumulator
}, {})
console.log(Object.values(result))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

lodash - convert an object into a sorted array based on the keys of the object

I want to use lodash to convert an object like this:
var a = {1:'a', 3:'b', 2:'c'};
into a sorted array of values based on the keys of the object like:
var result = ['a','c','b'];
I know I can do this:
var keyRef = Object.keys(a).sort();
var result = keyRef.map(v => a[v]);
But is this way optimized - is there any function in lodash which is more optimized for this??
With plain Javascript, you could use Object.values and take this array as sorted result, because if the keys of the object could be read as 32 bit integer numbers, Javascript use them in numerical order.
Source:
The traversal order of object properties in ES6
var object = { 1: 'a', 3: 'b', 2: 'c' },
values = Object.values(object);
console.log(values);
Using lodash,
const o = {1:'a', 3:'b', 2:'c'};
const res = _.sortBy(o, (a, b) => b);
console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.core.js"></script>
Lodash has the _.values(obj) function. However it is noted that the result ordering is not guaranteed. However, as #Nina pointed out, if you stick to ints as the keys, the ordering should be consistent (unless lodash is doing something weird).

Array sort() gives wrong answer in 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);

Change index of array values with keys

After running a function i am getting an array like this.
["1:s", "2:2", "0:f"]
but i want to convert this array like this
["0:f","1:s","2:2"]
i mean index should be same as key.
You could just sort it with taking the index out of the string.
var array = ["1:s", "2:2", "0:f"];
array.sort(function (a, b) {
return a.split(':')[0] - b.split(':')[0];
});
console.log(array);

Categories