P. Ishtik P. Ishtik - 1 year ago 94
Javascript Question

javascript - sorting array by order of another array

My goal is to sort this div

<div id="myDiv">3xOrange;2xBlue;1xRed;1xRed;1xRed;1xOrange;2xBlue;3xRed;1xBlue;1xRed;2xBlue;3xRed;1xBlue;1xRed;2xBlue;3xRed;1xBlue;1xRed;2xBlue;3xRed;1xBlue;1xRed;2xOrange;3xRed;1xBlue;1xRed;2xBlue;3xRed;1xBlue;1xRed;20xBlue;33xRed;20xBlue;33xRed;2xBlue;3xRed;51xBlue;51xRed;</div>

by another div in this order

<div id="array"> Blue: 1,Red: 2,Orange: 3, </div>

So my Wanted result is to get result like this

2xBlue;1xBlue;1xBlue;2xBlue;3xRed;3xRed;1xRed;1xRed;2xOrange;3xOrange ......

I aware for the first div needs to be used string split something like this

So far I have this code:

var init_arr;
var scorer;

window.onload=function() {
init_arr = document.getElementById("myDiv").innerHTML;

var final_arr = init_arr.sort(function(a,b) {
return scorer[a]-scorer[b];

but getting error
TypeError: init_arr.sort is not a function
I guess init_arr and scorer are objects not strings
Please Help

Answer Source

This answer deletes the rest of the strings with ; or ,, treats array like a part of a JSON string, and sort with the part after the x.

window.onload = function() {
    var init_arr = document.getElementById("myDiv").innerHTML.split(';'),
        scorer = JSON.parse('{' + document.getElementById("array").innerHTML + '}');

    init_arr.sort(function(a, b) {
        var aa = a.split('x')[1],
            bb = b.split('x')[1];
        return scorer[aa] - scorer[bb];
<div id="myDiv">3xOrange;2xBlue;1xRed;1xRed;1xRed;1xOrange;2xBlue;3xRed;1xBlue;1xRed;2xBlue;3xRed;1xBlue;1xRed;2xBlue;3xRed;1xBlue;1xRed;2xBlue;3xRed;1xBlue;1xRed;2xOrange;3xRed;1xBlue;1xRed;2xBlue;3xRed;1xBlue;1xRed;20xBlue;33xRed;20xBlue;33xRed;2xBlue;3xRed;51xBlue;51xRed</div>
<div id="array">"Blue": 1,"Red": 2,"Orange": 3</div>

But I really suggest to use real arrays for data and objects for sorting order. And not any parts of HTML code.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download