I've created a couple arrays. arrLocations holds a series of 2-digit country names, arrResults counts how many times each occurs and holds the country name with it's count as see here:
[
FR: 40, US: 1511, AU: 82,
CN: 151, IE: 170, SG: 108,
GB: 66, KR: 52, JP: 137,
IN: 45, BR: 68, SE: 39,
ZA: 19, NL: 19, BH: 19,
LU: 3, CA: 41, DE: 79,
ID: 1, HK: 1
]
My intention is to sort this array by ascending occurrence, I want this:
[
ID: 1, HK: 1, LU: 3,
BH: 19, NL: 19, ZA: 19,
....and so on........
]
However, no matter what way I implement sort, it does absolutely nothing. I even did a test sort on a dumby array and was able to sort it fine, but this array I cannot sort.
Here is what I have so far:
var geoip = require('geoip-lite')
const fs = require('fs')
const { Console } = require('console')
let data = fs.readFileSync('./ip_new.txt')
let iplocation = ""
let arrLocations = []
let arrResults = []
let arrIP = data.toString().split("\r\n")
for(let item of arrIP){
iplocation = geoip.lookup(item)
arrLocations.push(iplocation.country)
}
for(let item of arrLocations){
if (item in arrResults){
arrResults[item]++
}
else{
arrResults[item]=1
}
}
arrResults.sort()
console.log(arrResults)
OK, so first of all I'm assuming this
[
FR: 40, US: 1511, AU: 82,
CN: 151, IE: 170, SG: 108,
GB: 66, KR: 52, JP: 137,
IN: 45, BR: 68, SE: 39,
ZA: 19, NL: 19, BH: 19,
LU: 3, CA: 41, DE: 79,
ID: 1, HK: 1
]
Is actually this
[
{ FR: 40 }, { US: 1511 }, { AU: 82 },
{ CN: 151 }, { IE: 170 }, { SG: 108 },
{ GB: 66 }, { KR: 52 }, { JP: 137 },
{ IN: 45 }, { BR: 68 }, { SE: 39 },
{ ZA: 19 }, { NL: 19 }, { BH: 19 },
{ LU: 3 }, { CA: 41 }, { DE: 79 },
{ ID: 1 }, { HK: 1 }
]
If this is true, then sort method will not work on it's own. The following will do though:
const arrResults = [
{ FR: 40 }, { US: 1511 }, { AU: 82 },
{ CN: 151 }, { IE: 170 }, { SG: 108 },
{ GB: 66 }, { KR: 52 }, { JP: 137 },
{ IN: 45 }, { BR: 68 }, { SE: 39 },
{ ZA: 19 }, { NL: 19 }, { BH: 19 },
{ LU: 3 }, { CA: 41 }, { DE: 79 },
{ ID: 1 }, { HK: 1 }
];
arrResults.sort((a, b) => {
const countryCodeA = Object.keys(a)[0];
const countryCodeB = Object.keys(b)[0];
return a[countryCodeA] - b[countryCodeB];
});