Sort an Array with Arrays in It by String

Sort an array with arrays in it by string

This can be achieved by passing a supporting function as an argument to the Array.sort method call.

Something like this:

 function Comparator(a, b) {   if (a[1] < b[1]) return -1;   if (a[1] > b[1]) return 1;   return 0; }
var myArray = [ [1, 'alfred', '...'], [23, 'berta', '...'], [2, 'zimmermann', '...'], [4, 'albert', '...'], ];
myArray = myArray.sort(Comparator); console.log(myArray);

Sorting Array of Arrays with Strings in it

You could code:

function Comparator(a, b) {
// you can use the `String.prototype.toLowerCase()` method
// if the comparison should be case insensitive
if (a[1] < b[1]) return -1;
if (a[1] > b[1]) return 1;
if (a[0] < b[0]) return -1;
if (a[0] > b[0]) return 1;
return 0;
}

The above function at first sorts the elements based on the second element of the arrays. If the second elements are equal then it sorts them based on the first elements and if a[1] === b[1] and a[0] === b[0] it returns 0 which leaves the a and b positions unchanged.

From MDN Array.prototype.sort documentation:

If compareFunction is supplied, the array elements are sorted according to the return value of the compare function. If a and b are two elements being compared, then:

  • If compareFunction(a, b) is less than 0, sort a to a lower index than b, i.e. a comes first.
  • If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
  • If compareFunction(a, b) is greater than 0, sort b to a lower index than a.
    compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned then the sort order is undefined.

Sort array of arrays with string values [JavaScript]

Subtraction only works as the comparison function when you're comparing numbers. You need a comparison function that works with both numbers and strings.

function sortArr(a, b) {
if (a == b) {
return 0;
else if (a < b) {
return -1;
} else {
return 1;
}
}

Sort an array of arrays in JavaScript

You can pass a custom comparison function to Array.prototype.sort(), like so:

var sortedArray = array.sort(function(a, b) { return a - b; });

This would sort an array of integers in ascending order. The comparison function should return:

  • an integer that is less than 0 if you want a to appear before b
  • an integer that is greater than 0 if you want b to appear before a
  • 0 if a and b are the same

So, for this example you would want something like:

var sortedArray = array.sort(function(a, b) {
return b[0] - a[0];
});

If you wanted to sort on both elements of each sub-array (ie. sort by the first element descending, then if they are the same then sort by the second element descending), you could do this:

var sortedArray = array.sort(function(a, b) {
if (a[0] == b[0]) {
return a[1] - b[1];
}
return b[0] - a[0];
});

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort for more info.

Sort array of objects by string property value

It's easy enough to write your own comparison function:

function compare( a, b ) {
if ( a.last_nom < b.last_nom ){
return -1;
}
if ( a.last_nom > b.last_nom ){
return 1;
}
return 0;
}

objs.sort( compare );

Or inline (c/o Marco Demaio):

objs.sort((a,b) => (a.last_nom > b.last_nom) ? 1 : ((b.last_nom > a.last_nom) ? -1 : 0))

Or simplified for numeric (c/o Andre Figueiredo):

objs.sort((a,b) => a.last_nom - b.last_nom); // b - a for reverse sort

What is the most efficient way to sort an array of strings by another array of strings?

Use this:

let education = [
["Bob", "High School"],
["Alice", "Middle School"],
["Jane Doe", "Undergrad"],
["alex", "Middle School"],
["Mega Alice", "Middle School"],
["Jhon Doe", "Middle School"],
["Minor Bob", "Middle School"],
["Chicken", "Graduate"],
["Minor Chicken", "Elementary"],
["Clones", "Elementary"],
["Clones", "Elementary"],
["Clones", "Elementary"]
];

let educationLevel = ["Elementary", "Middle School", "High School", "Undergrad", "Graduate"];

function sortFunc(a, b) {
return educationLevel.indexOf(a[1]) - educationLevel.indexOf(b[1]);
}

education.sort(sortFunc);
console.log(education);

How to sort String array by length using Arrays.sort()

If you are using JDK 1.8 or above then you could use lambda expression like matt answer. But if you are using JDK 1.7 or earlier version try to write a custom Comparator like this:

String S = "No one could disentangle correctly";
String W[] = S.split(" ");
Arrays.sort(W, new java.util.Comparator<String>() {
@Override
public int compare(String s1, String s2) {
// TODO: Argument validation (nullity, length)
return s1.length() - s2.length();// comparision
}
});

How to sort an array of Strings based on the parsed first digit

You can split each string on \D (which means non-digit) and compare the strings based on the first elements, parsed into an integer, of the resulting arrays.

Demo:

import java.util.Arrays;

public class Main {
public static void main(String[] args) throws InterruptedException {
String[] array = { "18.sdfahsdfkjadf", "1.skjfhadksfhad", "2.asldfalsdf" };

Arrays.sort(array,
(s1, s2) ->
Integer.compare(
Integer.parseInt(s1.split("\\D")[0]),
Integer.parseInt(s2.split("\\D")[0])
)
);

System.out.println(Arrays.toString(array));
}
}

Output:

[1.skjfhadksfhad, 2.asldfalsdf, 18.sdfahsdfkjadf]

Sort List of string arrays by first element

Stream.sorted() takes a comparator (in addition to the overload that takes no argument). So all you need is ...sorted(byFirstElement)... (the stream sorts its elements)

Note that your comparison logic won't sort in descending order, so you either need to change it to

Comparator<String[]> byFirstElement = 
(array1, array2) -> Integer.parseInt(array2[0]) - Integer.parseInt(array1[0]);
//reversed

or reverse it when calling sorted():

....sorted(byFirstElement.reversed())

Python: get the indices that would sort an array of strings to match another array of strings

A vectorised approach is possible via numpy.searchsorted together with numpy.argsort:

import numpy as np

A = np.array(['a', 'b', 'c', 'd'])
B = np.array(['d', 'b', 'a', 'c'])

xsorted = np.argsort(B)
res = xsorted[np.searchsorted(B[xsorted], A)]

print(res)

[2 1 3 0]


Related Topics



Leave a reply



Submit