javascript sort array by inside data - javascript

I need to sort an array by his inside first element data .
my array looks something like that
arr = [[0,"lol"][6,"yo"][5,"comon"]]
After the sorting I need it to be like that :
[[0,"lol"][5,"comon"][6,"yo"]]
0 , 5 , 6 suppose to order the cells and they data they have is irrelevent.
Thanks.

You can try something like this...
Live Demo
I made ​​some changes...
Corrected the mistake :
// before that I'm checking arrays and not a values of it...
(!isNaN(a) && !isNaN(b)) to (!isNaN(a[0]) && !isNaN(b[0]))
and to ignore case...
aa = a[0].toString().toLowerCase();
bb = b[0].toString().toLowerCase();
===========================================================
arr.sort(function (a, b) {
var aa, bb;
if (!isNaN(a[0]) && !isNaN(b[0])) {
return a[0] - b[0];
} else {
aa = a[0].toString().toLowerCase();
bb = b[0].toString().toLowerCase();
return (aa == bb) ? 0 : (aa < bb) ? -1 : 1;
}
});

jsfiddle Link
var arr = [[0,"lol"],[6,"yo"],[5,"comon"]];
arr.sort(function(a, b) {
return a[0] - b[0];
});

Use this code to sort your array..
var arr = [[0,"lol"],[6,"yo"],[5,"comon"]];
arr.sort(function(a, b) {
if (a[0] == b[0]) {
return 0;
} else {
return a[0] < b[0] ? -1 : 1;
}
});

Related

How to sort A-a-Z-z a list of names?

I need to sort a list of data by alphabetical order but in A-a-Z-z, were the name Antony comes before the name antony and Zelda comes before zelda so the list looks like this:
- Abigail
- Antony
- abigail
- antony
- Zelda
- zelda
The basic
list.sort(function (a, b) {
if (a.name > b.name) return -1;
if (a.name < b.name) return 1;
return 0;
});
is producing a list like this:
Abigail
Antony
Zelda
abigail
antony
zelda
preferable language: Javascript
There is a built-in for that:
let list = ["abigail", "Antony", "Abigail", "antony", "Zelda", "zelda"];
list.sort((a, b) =>
a.localeCompare(b, "en", { caseFirst: "upper" })
);
console.log(list);
EDIT: maybe you want this?
let list = ["abigail", "Antony", "Abigail", "antony", "Zelda", "zelda"];
const compareUpperFirst = (a, b) => {
if (a === "" && bb === "") return 0;
if (a === "") return -1;
if (b === "") return 1;
let aa = a.charAt(0);
let aal = aa.toLowerCase();
let bb = b.charAt(0);
let bbl = bb.toLowerCase();
if (aal < bbl) return -1;
if (aal > bbl) return 1;
if (aa < bb) return -1;
if (aa > bb) return 1;
return compareUpperFirst(a.substr(1), b.substr(1));
};
list.sort(compareUpperFirst);
console.log(list);

Alphabetical array sort - lowercase first

Given the array :
var myArray = ['d','a','k','v','z','A','t','G']
If I were to use :
myArray.sort()
The result would be :
myArray = ['A','G','a','d','k','t','v','z']
Is there a way of modifying the sort function or the output to put the uppercase letters at the end of the array like this :
myArray = ['a','d','k','t','v','z','A','G']
Either pure Javascript or jQuery would be OK.
Test the first character and apply compare:
var myArray = ['d', 'a', 'k', 'v', 'z', 'A', 't', 'G', 'V'];
myArray.sort(function (a, b) {
if (a[0] === a[0].toLocaleLowerCase() && b[0] === b[0].toLocaleLowerCase() ||
a[0] === a[0].toLocaleUpperCase() && b[0] === b[0].toLocaleUpperCase()) {
return a.localeCompare(b);
}
if (a[0] === a[0].toLocaleLowerCase()) {
return -1;
}
return 1;
});
document.write('<pre>' + JSON.stringify(myArray, 0, 4) + '</pre>');
Here's an example of the array sort using the compare function:
myArray.sort(function(a, b){
var test = a.charCodeAt(0) <= 90 && b.charCodeAt(0) <= 90;
if(test) return a.charCodeAt(0)-b.charCodeAt(0);
else if(a.charCodeAt(0) <= 90) return 1;
else if(b.charCodeAt(0) <= 90) return -1;
else return a.charCodeAt(0)-b.charCodeAt(0);
});
You should use custom compare function myArray.sort(compareFunction). Inside of the function you can use
conditions like if(a === a.toUpperCase()) and so on to create logic that you need.
var myArray = ['d','a','k','v','z','A','t','G'];
_.each(myArray, function(item){
if(item.charCodeAt(0) > 96){
smallArr.push(item)
}
else{
captArray.push(item)
}
});
smallArr.sort();
captArray.sort();
myArray = [];
myArray.push.apply(myArray, smallArr.concat(captArray));
once you have got this array
myArray = ['a','d','k','t','v','z','A','G']
do this to get it sorted by myArray = ['A','G','a','d','k','t','v','z']
var tempArray = myArray.join("").split(/(?=[A-Z])/);
myArray = tempArray.slice(1).concat( tempArray [0].split("") );

How to sort array of strings based on a contained number?

I have an array with strings like this:
"1115.49|Onroll|Paiporta|/v2/networks/onroll-paiporta"
"1767.92|Göteborg|Göteborg|/v2/networks/goeteborg"
"190.4|ARbike|Arezzo|/v2/networks/arbike"
"201.36|JesinBici|Jesi|/v2/networks/jesinbici"
"403.59|Venezia|Venezia|/v2/networks/venezia"
"395.07|Mantova|Mantova|/v2/networks/mantova"
the first value is a distance, I would like to sort the array based on that distance, how can I do?
Everything I've tried does not work, I would that 1000 come after 200 not before!
thanks!
You can do something like this:
yourArray.sort(function (a, b) {
var aNum = +a.substring(0, a.indexOf('|'));
var bNum = +b.substring(0, b.indexOf('|'));
if (aNum > bNum) return 1;
if (aNum < bNum) return -1;
return 0;
});
which will return an array in the ascending order you wanted.
If you add a sortBy function to Array.prototype you can do things like that more easily.
Array.prototype.sortBy = function(f) {
this.sort(function(a, b) {
a = f(a); b = f(b);
if(a > b) return 1;
if(a < b) return -1;
return 0;
});
}
and then you can write
array.sortBy(function(s) { return +s.split("|")[0]; });

How to sort objects by date ascending order?

If I have a list of object:
var objectList= LIST_OF_OBJECT;
each object in the list contains three attributes: "name", "date","gender"
How to sort the objects in the list by "date" attribute ascending order?
(the "date" attribute contain string value like "2002-08-29 21:15:31+0500")
If your objects have the date information within a String field:
yourArray.sort(function(a, b) { return new Date(a.date) - new Date(b.date) })
or, if they have it within a Date field:
yourArray.sort(function(a, b) { return a.date - b.date })
The Array.sort method accepts a sort function, which accepts two elements as arguments, and should return:
< 0 if the first is less than the second
0 if the first is equal to the second
> 0 if the first is greater than the second.
.
objectList.sort(function (a, b) {
var key1 = a.date;
var key2 = b.date;
if (key1 < key2) {
return -1;
} else if (key1 == key2) {
return 0;
} else {
return 1;
}
});
You're lucky that, in the date format you've provided, a date that is before another date is also < than the date when using string comparisons. If this wasn't the case, you'd have to convert the string to a date first:
objectList.sort(function (a, b) {
var key1 = new Date(a.date);
var key2 = new Date(b.date);
if (key1 < key2) {
return -1;
} else if (key1 == key2) {
return 0;
} else {
return 1;
}
});
yourArray.sort(function(a, b) {
a = new Date(a.date);
b = new Date(b.date);
return a >b ? -1 : a < b ? 1 : 0;
})
You can try:
<script src="https://cyberknight.000webhostapp.com/arrange.js">
var a =[-1,0,5,4,3,2,6,1,1];
var b = totzarrange(a)
console.log(b);
</script>

How to find out the position of the first occurrence of the difference between the two string?

For example, Hello World! and Hi World! - the first occurrence of the difference is at the second character. What would be the JavaScript/jQuery function?
Assuming, like other answers, that matching strings return -1:
// Find common prefix of strings a and b.
var prefix = function(a,b){
return a && a[0] === b[0] ? a[0] + prefix(a.slice(1), b.slice(1)) : '';
};
// Find index of first difference.
var diff = function(a,b){
return a===b ? -1 : prefix(a,b).length;
};
var tests = [
['Hello World!', 'Hi World!'],
['aaabab', 'aaabzbzz'],
['', ''],
['abc', 'abc'],
['qrs', 'tu'],
['abc', ''],
['', 'abc']
];
console.log('diff', tests.map(test => diff(test[0], test[1])));
// Or just count up to the first difference
// Trickier nested ternary to handle the -1 however.
var diff2 = function(a,b){
return a === b ? -1 : a[0] === b[0] ? 1 + diff2(a.slice(1), b.slice(1)) : 0;
};
console.log('diff2', tests.map(test => diff2(test[0], test[1])));
Maybe something like this? It returns, in that order, the position of the first
difference if there's any, the length of the shortest string if those are different, or -1 if everything is equal.
function findDiff(a, b) {
a = a.toString();
b = b.toString();
for (var i = 0; i < Math.min(a.length, b.length); i++) {
if (a.charAt(i) !== b.charAt(i)) { return i; }
}
if (a.length !== b.length) { return Math.min(a.length, b.length); }
return -1;
}
Thanks Phil for the suggestions!
function strDiff(first, second) {
if(first==second)
return -1;
first = first.toString();
second = second.toString();
var minLen = min(first.length,second.length);
for(var i = 0; i<minLen; i++) {
if(first.charAt(i) != second.charAt(i)) {
return i;
}
}
return minLen;
}
Returns -1 if the strings do not differ, or the index (starting at 0) of the character at which they do (this is the length of the shortest string if they only differ by being different lengths, e.g. 'abcd' and 'abcdef' would return 4.
function firstDiff(a, b) {
var i = 0;
while (a.charAt(i) === b.charAt(i))
if (a.charAt(i++) === '')
return -1;
return i;
}
Returns the position where the two strings a and b first differ or -1 if they are equal.
A more efficient but less readable version:
function firstDiff(a, b) {
for (var i = 0, c; (c = a.charAt(i)) === b.charAt(i); ++i)
if (c === '')
return -1;
return i;
}
If you feel that you should first stringify the arguments, then do it in the invocation:
firstDiff(toString(a), toString(b))
Most often that will be a waste of time. Know your data!

Categories

Resources