简体   繁体   中英

How do I sort one array by the corresponding values in another array?

I have two arrays. The first is for strings and the second is an array for their number of occurrences.

I am trying to get the top 10 most occurrences of words in the first array. I sorted it but somehow I only sort it alphabetically and the second array respectively corresponds to their number of occurrences.

How can I sort the second array from biggest to lowest and, at the same time, sort the first array that match the order of the second ?

I'm having trouble inserting my json to my highcharts and I found out why, the numbers should be in square brackets [] I tried already inserting [] in 1 but still does not work please see my post I edit it

this is the data that i should insert in the highchart

[{"name":"#murrayftw","data":[46]},
 {"name":"#job","data":[37]},
 {"name":"#jobs","data":[25]},
 {"name":"#favnashvine","data":[16]},
 {"name":"#rollersmusicawards","data":[14]},
 {"name":"#soa","data":[13]},
 {"name":"#tweetmyjobs","data":[12]},
 {"name":"#sman1boyolangu","data":[12]},
 {"name":"#supernatural200thepisode","data":[12]},
 {"name":"#veteransday","data":[12]}]

Try using a custom compare function with your .sort() call! Check out the documentation here.

I would, in this example (probably not the best way):

  1. Have the unsorted "count" array
  2. Have the unsorted word array
  3. Sort the word array (with a custom function described below)
  4. Sort the count array (no custom function)

The custom compare function would probably be a simple lookup and return the corresponding value in the unsorted count array. (ie if the word "a" is 0th index and its relevant count amount is in the 0th index of the count array, return count[0])

If you cannot work with an object try using nested for loops:

var array1 = ['z', 'd', 'e', 'f', 't'], arr1Count = array1.length;
var array2 = [1, 12, 5, 7, 3];
var sortedArray2 = array2.sort(function(x, y) {return y - x});

var i, j, sortedArray1 = [];

for (i = 0; i < arr1Count; i++) {
    for (j = 0; j < arr1Count; j++) {
        if (array2[j] === sortedArray2[i]) sortedArray1.push(array1[j]); //iterate through the unsorted numeric array (array2) and when it matches the sortedArray2, push this index of array1 into the sortedArray1
    }
}

This will create an array of objects that are then sorted by count.

var hashtags = {},
    counts = [];

for (var i in data)
{
    if(data[i].lang == "en")
    {   
        for (var j in data[i].entities.hashtags)
        {
            var text = data[i].entities.hashtags[j].text;

            if(text) {
                if(hashtags[text]) {
                     hashtags[text].data[0]++;
                } else {
                     hashtags[text] = {
                         name: text,
                         data: [1]
                     };
                     counts.push(hashtags[text]);
                }
            }
        }
    }
}

counts.sort(function(a, b) { return b.data[0] - a.data[0]; });

Simple - don't use 2 arrays but one collection which every element is an object

I took the basics from this post: Sorting JavaScript Object by property value

and completed the demo:

var collection = {car:300, bike:60, motorbike:200, airplane:1000, helicopter:400, rocket:8*60*60}
var sortable = [];
for (var item in collection)
      sortable.push([item, collection[item]])
sortable.sort(function(a, b) {return a[1] - b[1]})

collection = {};
for (var i in sortable)
{
    collection[sortable[i][0]] = sortable[i][1];
}

console.log(collection);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM