DEV Community

Jeena John
Jeena John

Posted on

Data Structures and Algorithms in Javascript - Part 3

This is Part 3 of my series of posts on Data Structures and Algorithms in Javascript...to get you started.

In Part 3, we will cover

  • Most frequently occurring item in an array
  • Sum of elements of a nested array
  • Array chunks

1. Find the most frequently occurring item in an array

Here, a hash table is used to store each element of the array and its frequency (count) as key-value pairs.

let array = [2, 4, 1, 6, 1, 40, 1, 2, 4, 10, 1]; function mostFrequent(arr) { let hashMap = {}; let mostFreq = { value: undefined, count: 0 }; for (let i = 0; i < arr.length; i++) { if (!hashMap[arr[i]]) { hashMap[arr[i]] = 1; //set count to 1 initially } else { ++hashMap[arr[i]]; //increment count } if (mostFreq.count < hashMap[arr[i]]) { //make the new element the most frequent one mostFreq.value = arr[i]; mostFreq.count = hashMap[arr[i]]; } } return mostFreq.value; } console.log(mostFrequent(array)); 
Enter fullscreen mode Exit fullscreen mode

2. Find the sum of elements of a nested array

Recursion is used to find the sum.

let array = [1, 2, 3, [4, 5], [6, 7, [8, 9]]]; function findSum(arr) { let sum = 0; for (let i = 0; i < arr.length; i++) { if (arr[i].length > 1) { sum += findSum(arr[i]); //nested array } else { sum += arr[i]; } } return sum; } console.log(findSum(array)); 
Enter fullscreen mode Exit fullscreen mode

3. Split an array into chunks

let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; function chunkArray(arr, size) { let chunk = []; let result = []; for (let i = 0; i < arr.length; i++) { if (chunk.length < size) { chunk.push(arr[i]); } else { result.push(chunk); //add chunk to result chunk = []; // reset chunk chunk.push(arr[i]); } } if (chunk.length > 0) { result.push(chunk); } return result; } console.log(chunkArray(array, 3)); 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)