javascript/jQuery sort array [duplicate] - javascript

This question already has answers here:
Sort Array Elements (string with numbers), natural sort
(8 answers)
Closed 8 years ago.
I have an array of values that look like this:
var myArr = ["S1_FORM", "S3_FORM", "S2_FORM", "S2_2_FORM"];
I need to sort them from lowest to highest.
The way I would like this array to be is like this:
["S1_FORM", "S2_FORM", "S2_2_FORM", "S3_FORM"]
Basically these numbers should be read like: 1, 2, 2.2, 3
How could I achieve this?
I have tried using .sort() but it returns:
["S1_FORM", "S2_2_FORM", "S2_FORM", "S3_FORM"]
notice "2_2" comes before "2_". It shouldn't.

var myArr = ["S1_FORM", "S3_FORM", "S2_FORM", "S2_2_FORM"];
var extractNumber = function(str) {
var m = str.match(/^S(\d+)_(?:(\d+)_)?/);
return parseFloat(m[1] + '.' + m[2])
};
myArr.sort(function(a, b) {
return extractNumber(a) - extractNumber(b);
});
console.log(myArr);
http://jsfiddle.net/LDphK/
So you're extracting a number using trivial regular expression and then sort it using Array.prototype.sort()

var myArr = ["S1_FORM", "S3_FORM", "S2_FORM", "S2_2_FORM"];
myArr.sort();
If you need another sorting logic, use jQuery. This is vanilla JavaScript solution

Related

How to sort an array using regex in Javascript? [duplicate]

This question already has answers here:
Natural sort of alphanumerical strings in JavaScript
(6 answers)
Closed 2 years ago.
I have an array which looks like this
arr = ["#0abc", "#2egf", "#0pol kol", "#1loa", "#2ko pol"]
As you can see, each element in the array has #n associated with it where n is any number between 0-9. Now based on the n, I want to sort by array in ascending order such that the final output looks like this
[ '#0abc', '#0pol kol', '#1loa', '#2egf', '#2ko pol' ]
So this is what I do
rankWordMap = {}
finalArr = []
arr.forEach(function(entry) {
rank = entry.charAt(1)
if(rankWordMap[rank]) {
rankWordMap[rank].push(entry);
}
else {
rankWordMap[rank] = [entry];
}
})
for (var key in rankWordMap) {
if (rankWordMap.hasOwnProperty(key)) {
finalArr.push(...rankWordMap[key])
}
}
console.log(finalArr)
I get the expected output but as you can see, it's pretty inefficient. Besides I could have hundreds of elements sometimes where I would like to quickly sort it rather than doing it this way.
Is there any shorter way to implement this? I am specifically looking for a regex solution but other solutions are fine too.
No need for regex, just sort based on the integer value of the second character in each entry:
arr = ["#0abc", "#2egf", "#0pol kol", "#1loa", "#2ko pol"];
arr.sort((a, b) => parseInt(a[1]) - parseInt(b[1]));
console.log(arr);
You could match the first coming digits and take this value for sorting.
var
getValue = string => string.match(/\d+/),
array = ["#0abc", "#2egf", "#0pol kol", "#1loa", "#2ko pol"];
array.sort((a, b) => getValue(a) - getValue(b));
console.log(array);

How to correctly sort a string array in javascript [duplicate]

This question already has answers here:
Natural sort of alphanumerical strings in JavaScript
(6 answers)
Closed 2 years ago.
I have an array that looks like the following
const files = ['30.png', '10.png', '1.jpeg', '2.jpeg', '12.gif', '4.png']
I wanna sort it in numerical order but just calling sort is a problem because when sorted it will look like this:
['1.jpeg', '10.png', '12.gif', '2.jpeg', '30.png', '4.png']
How can I sort it in a "correct" way so that it looks like this
[ '1.jpeg', '2.jpeg', '4.png', '10.png', '12.gif', '30.png']
We can use the following code:
const files = ['30.png', '10.png', '1.jpeg', '2.jpeg', '12.gif', '4.png'];
function fileToNumber(file) {
// we get everything before the period and convert it to a number
return parseInt(file.split(".")[0], 10);
}
// we sort with a custom comparator based on our fileToNumber function
files.sort((a, b) => fileToNumber(a) - fileToNumber(b));
function numberPart (str){
return parseInt(str.split('.')[0])
}
const files = ['30.png', '10.png', '1.jpeg', '2.jpeg', '12.gif', '4.png'];
files.sort( (a,b) => numberPart(a) - numberPart(b))
console.log(files)

Find partial string in array [duplicate]

This question already has answers here:
How do you search an array for a substring match?
(15 answers)
Closed 3 years ago.
var fruits = ["CarPaint.InString.Banana", "CarPaint.InString.Orange", "CarPaint.InString.Apple", "CarPaint.InString.Mango"];
var n = fruits.includes("Mango");
Let's say you don't know whats inside the fruits array ?
How do you extract the string that contains mango.
The prefix string must be included in the result.
Can this be done without a for loop and parsing ?
var fruits = ["CarPaint.InString.Banana", "CarPaint.InString.Orange", "CarPaint.InString.Apple", "CarPaint.InString.Mango"];
var n = fruits.includes("Mango");
console.log(n)
You need to filter the array and check each string.
var fruits = ["CarPaint.InString.Banana", "CarPaint.InString.Orange", "CarPaint.InString.Apple", "CarPaint.InString.Mango"],
result = fruits.filter(string => string.includes("Mango"));
console.log(result);
How about the following?
fruits.filter(fruit => fruit.includes('Mango'))
// [ 'CarPaint.InString.Mango' ]

Sort array of array on string value in Javascript [duplicate]

This question already has answers here:
Sort array of objects by string property value
(57 answers)
Closed 6 years ago.
I want to sort the array of array on length of string, as follows
var arr = [
[1951, "Mayfer"],
[1785, "Actinac Capsules"],
[1007, "Ferri Injection"],
[1101, "Cetaphil"]
];
var sortedArr = sortOnLengthOfString(arr);
>> sortedArr = [
[1951, "Mayfer"],
[1101, "Cetaphil"],
[1007, "Ferri Injection"],
[1785, "Actinac Capsules"]
]
Is there a solution with lodash preferably? Or plain Javascript?
I haven't found duplicate question yet. Can someone find it? Please note, the sorting I am asking for, is for array of arrays and not array of objects.
You can use Array#sort at this context,
var obj = [
[1951, "Mayfer"],
[1785, "Actinac Capsules"],
[1007, "Ferri Injection"],
[1101, "Cetaphil"]
];
obj.sort(function(a,b){
return a[1].length - b[1].length
});
console.log(obj);
//[[1951, "Mayfer"],[1101, "Cetaphil"],[1007, "Ferri Injection"],[1785, "Actinac Capsules"]]

Is possible to combine two arrays? "array.join(array)"? [duplicate]

This question already has answers here:
zip two arrays Javascript [duplicate]
(3 answers)
Closed 8 years ago.
I have two arrays:
var array1= [[1],[2],[3]];
var array2= [[10],[20],[30]];
is there a way to (have) a third array?
var array3 = [[1],[10],[2],[20],[3],[30]];
Maybe:
var test= array1.join(array2 + "<br>");
I think you are looking for the "concat" function
Join two arrays:
var hege = ["Cecilie", "Lone"];
var stale = ["Emil", "Tobias", "Linus"];
var children = hege.concat(stale);
The values of the children array will be:
Cecilie,Lone,Emil,Tobias,Linus
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat
You can either use CONCAT function like
array1 = array1.concat(array2)
OR, APPLY()
array1.push.apply(array1, array2)

Categories

Resources