The sort function can be very handy if we want our array/Object elements returned in ascending or descending order. It is a quicker way rather than trying to sort the array elements yourself. In this article, we are going to go through an interesting exercise where we have an array with 500 ip addresses, some of them repeated more than others. We want to display the top ten repeated ip addresses.
We are first going to determine the count of each IP address then from the count, we will sort the array using the sort function and return the top 10 IP addresses.
We can generate our IP addresses using JavaScript. Hopefully we will be able to get some IP addresses being repeated at random so that we can see the power of the sort() function based on count. Have the following code in a JavaScript file and name the file generateIPs.js
:
async function generateIPAddresses(totalIPs, repeatedIPs) {
const ipAddresses = [];
for (let i = 0; i < totalIPs; i++) {
let ip;
if (i < repeatedIPs.length) {
ip = repeatedIPs[i];
} else {
ip = `${Math.floor(Math.random() * 256)}.${Math.floor(
Math.random() * 256
)}.${Math.floor(Math.random() * 256)}.${Math.floor(Math.random() * 256)}`;
}
ipAddresses.push(ip);
}
return ipAddresses;
}
// const ipAddresses = generateIPAddresses(100, ["137.4.80.85","137.4.80.85","137.4.80.85","17.218.207.93","17.218.207.93","17.218.207.93","17.218.207.93","17.218.207.93"]);
// console.log(ipAddresses);
module.exports = { generateIPAddresses };
The second function parameter repeatedIPs
expects an array of IP addresses we want repeated just to show that our sort function will work. The parameter ensures that we have some repeated IP addresses without it, we may find ourselves with each IP address appearing once.
In this expression Math.floor(Math.random() * 256)
, Math.floor is used to round down a number to the nearest integer. Math.Random generates a random number while using it liek this Math.random() * 256
generates a random octet (unit of 8 bits; IPv4 has 8 x 4 bits in total that's why we write this expression 4 times). You can preview the result using the console.log(...)
. If you have Node.js on your machine you should be able to run:
node generateIPs.js
in a terminal where the file exists and preview your IP addresses in the terminal.
Create another file still in the same location where you had the generateIPs.js
file and call it sortingIPs.js
. We will import generateIPAddresses()
from the generateIPs.js
file and use it to generate our IP addresses array then count the occurrences of each IP address then use sort()
.
Using the sort() function, we will have an Object(ipCount
) sorted in descending order then display the top 10 repeated IPs. Have the following code inside sortingIPs.js
file:
const generateIPs = require("./generateIPs");
let ipAddresses = [];
let repeatedAddresses = [
"137.4.80.85",
"133.119.253.208",
"17.218.207.93",
"137.4.80.85",
"17.218.207.93",
"133.119.253.208",
"17.218.207.93",
"140.241.78.108",
"17.218.207.93",
"137.4.80.85",
"60.181.91.123",
"17.218.207.93",
"133.119.253.208",
"60.181.91.123",
"133.119.253.208",
"17.218.207.93",
"140.241.78.108",
];
generateIPs.generateIPAddresses(500, repeatedAddresses).then(
(result) => {
ipAddresses = result;
// Count the occurrences of each IP address using an object
const ipCount = {};
ipAddresses.forEach((ip) => {
if (ipCount[ip]) {
ipCount[ip]++;
} else {
ipCount[ip] = 1;
}
});
// Sort the IP addresses by their count in descending order
let sortedIps = Object.entries(ipCount).sort((a, b) => b[1] - a[1]);
// Displaying the top 10 repeated IP addresses
for (let i = 0; i < 10; i++) {
const [ip, count] = sortedIps[i];
console.log(`${ip}: ${count} occurrences`);
}
},
(error) => {
console.log(error);
}
);
We are using .then()
here generateIPs.generateIPAddresses(500, repeatedAddresses).then(...)
because the function to generate IP addresses is an async function. Learn more about async/await
in JavaScript here.
The ipCount
object holds the occurrence of each IP address. The IP address itself is the key in the object and the count is the value (key/value pairs).
Again, if you have Node.js on your machine you should be able to run:
node sortingIPs.js
in a terminal where the file exists and see the list of the top 10 occurrences.
In the above code, we have used Object.entries(ipCount).sort((a, b) => b[1] - a[1]);
to sort in descending order based on the object count value i.e.: b[1]-a[1]
. If we wanted ascending order, meaning the bottom 10 repeated IPs, it would have been a[1]-b[1]
. The reason for the numbers inside the compare function i.e: a[1]
is because Object.entries() method returns an array of key-value pairs and we want to arrange based on count and not the IP address itself. If we wanted to use the IP address, we could have something like this: b[0]-a[0]
.
The sort is much simpler when used with arrays:
const myArray = [...];
myArray.sort(function(a, b){return a - b}); // ascending order
myArray.sort(function(a, b){return b - a}); // descending order
function(a, b){return a - b} // the compare function
We have seen how we can use the sort()
function for sorting both Object and Array items. I hope this article has helped you to learn about the sort()
function. You can let me know in the comments.