aNewStart847
aNewStart847

Reputation: 1076

Sorting an array according to defined order

I am trying to sort all items in the array items to follow the order specified in string. I am trying to get results to be

["first", "second", "third", "last"]

after sorting. The starting array has a randomized order.

var string = "first;second;third;last",
    items = ["third", "first", "last", "second"],
    result = [],
    lastpos = 0,
    lastinsert = 0;

for (var i = 0; i < items.length; i++) {
	var mypos = string.indexOf(items[i]),
	    insertat;
	if (mypos > lastpos) {
		insertat = lastinsert
	} else {
		insertat = lastinsert + 1
	}
	result.splice(insertat, 0, items[i]);
	lastpos = mypos;
}

document.getElementById("output").innerHTML = JSON.stringify(result);
<pre id="output"></pre>

I am not asking to have textual analysis to sort the array. The array should simply follow the order of the items in the variable string.

Upvotes: 0

Views: 497

Answers (2)

user3886234
user3886234

Reputation:

I'm assuming that you are asking more about the process to sort an array based on the values / indexes of another. Otherwise, there would be no reason to sort.

You can try using Array.prototype.sort() with something like this:

var string = "first;second;third;last".split(';'),
    items = ["third", "first", "last", "second"],
    result = [];

result = items.sort(function(a,b) {
    return string.indexOf(a) - string.indexOf(b) 
});

document.getElementById("output").innerHTML = JSON.stringify(result);

Here's a JSFiddle example.

--edit--

As per the comments, this should be more performance-friendly:

var string = "first;second;third;last".split(';'),
    stringHash = {},
    items = ["third", "first", "last", "second"],
    result = [];    

for (var i = 0, j = string.length; i < j; i++) {
    stringHash[string[i]] = i;
}

result = items.sort(function(a,b) {
    return stringHash[a] - stringHash[b];
});

document.getElementById("output").innerHTML = JSON.stringify(result);

You will be adding in an extra step, so if the original arrays are small it may not be worth it. If the arrays are larger, though, this will perform significantly better.

Upvotes: 3

Dashiel N
Dashiel N

Reputation: 319

I'm not sure I'm understanding correctly, but if your goal is simply to get an array of those elements in the original order, it would be simplest just to re-split from the original string:

var string = "a:test;a:second;b:third;a:last";
var result = string.split(';');

Or is there some transformation being performed on the data that's not depicted in the snippet there, that actually requires to you un-sort the existing array elements?

Upvotes: 0

Related Questions