Instructions for iterating through an array of objects, tracking a specific value, and ultimately displaying the most frequently occurring object

I've been attempting to extract the top n languages from an array of country objects and present them as an object containing the language and its count value. My approach involved using nested loops, but I encountered a roadblock in the process. Below is a snippet showcasing the array of country Objects...

const countries = [
{
 name: 'Afghanistan',
 capital: 'Kabul',
 languages: ['Pashto', 'Uzbek', 'Turkmen'],
 population: 27657145,
 flag: 'https://restcountries.eu/data/afg.svg',
 currency: 'Afghan afghani'
},
{
 name: 'Åland Islands',
 capital: 'Mariehamn',
 languages: ['Swedish'],
 population: 28875,
 flag: 'https://restcountries.eu/data/ala.svg',
 currency: 'Euro'
},
{
 name: 'Albania',
 capital: 'Tirana',
 languages: ['Albanian'],
 population: 2886026,
 flag: 'https://restcountries.eu/data/alb.svg',
 currency: 'Albanian lek'
},
{
 name: 'Algeria',
 capital: 'Algiers',
 languages: ['Arabic'],
 population: 40400000,
 flag: 'https://restcountries.eu/data/dza.svg',
 currency: 'Algerian dinar'
},
{
 name: 'American Samoa',
 capital: 'Pago Pago',
 languages: ['English', 'Samoan'],
 population: 57100,
 flag: 'https://restcountries.eu/data/asm.svg',
 currency: 'United State Dollar'
},
{
 name: 'Andorra',
 capital: 'Andorra la Vella',
 languages: ['Catalan'],
 population: 78014,
 flag: 'https://restcountries.eu/data/and.svg',
 currency: 'Euro'
},
{
 name: 'Angola',
 capital: 'Luanda',
 languages: ['Portuguese'],
 population: 25868000,
 flag: 'https://restcountries.eu/data/ago.svg',
 currency: 'Angolan kwanza'
},
{
 name: 'Anguilla',
 capital: 'The Valley',
 languages: ['English'],
 population: 13452,
 flag: 'https://restcountries.eu/data/aia.svg',
 currency: 'East Caribbean dollar'
}]

The expected output should resemble this


// Desired output format
console.log(mostSpokenLanguages(countries, 5))
/*[
{country: 'English',count:91},
{country: 'French',count:45},
{country: 'Arabic',count:25},
{country: 'Spanish',count:24},
{country:'Russian',count:9}
]*/

This is my attempted solution


const mostSpokenLanguage = (arr, count) => {
let languageCountObjArr = [];
let languagesArr = arr.map(countryObj => countryObj.languages);
console.log('Languages Array', languagesArr);
languagesArr.forEach(languageArr => {
 for (let i = 0; i < languageArr.length; i++) {
   /* Hit a snag here
     let langObj = {
     country: languageArr[i],
     count: 1
   };
   if (languageCountObjArr[i].country === languageArr[i]) {
     let
   }*/
   languageCountObjArr.push(langObj);
 }
});
languageCountObjArr = languageCountObjArr.slice(count);
return languageCountObjArr;
};

As someone relatively new to JavaScript, I'm still navigating through these challenges. Any assistance on this query would be greatly appreciated.

Answer №1

Here is an example:

const data = [{name: 'Japan',capital: 'Tokyo',languages: ['Japanese'],population: 126476461,flag: 'https://restcountries.eu/data/jpn.svg',currency: 'Japanese yen',},{name: 'India',capital: 'New Delhi',languages: ['Hindi', 'English'],population: 1339180127,flag: 'https://restcountries.eu/data/ind.svg',currency: 'Indian rupee',},{name: 'Brazil',capital: 'Brasília',languages: ['Portuguese'],population: 207353391,flag: 'https://restcountries.eu/data/bra.svg',currency: 'Brazilian real',}]

const languageCount = data.reduce((acc, { languages }) =>
  (languages.forEach((l) => (acc[l] = (acc[l] || 0) + 1)), acc), {})

const sortedLanguages = Object.entries(languageCount)
  .map(([language, count]) => ({ language, count }))
  .sort((a, b) => b.count - a.count)

console.log(sortedLanguages)

Answer №2

Implementing a dynamic approach using an array of objects and their properties to calculate the occurrence count.

const countries = [
{
 name: 'Afghanistan',
 capital: 'Kabul',
 languages: ['Pashto', 'Uzbek', 'Turkmen']
},
{
 name: 'Åland Islands',
 capital: 'Mariehamn',
 languages: ['Swedish']
},
{
 name: 'Albania',
 capital: 'Tirana',
 languages: ['Albanian']
},
{
 name: 'Algeria',
 capital: 'Algiers',
 languages: ['Arabic']
},
{
 name: 'American Samoa',
 capital: 'Pago Pago',
 languages: ['English', 'Samoan']
},
{
 name: 'Andorra',
 capital: 'Andorra la Vella',
 languages: ['Catalan']
},
{
 name: 'Angola',
 capital: 'Luanda',
 languages: ['Portuguese']
},
{
 name: 'Anguilla',
 capital: 'The Valley',
 languages: ['English']
}]
function groupBy(objectArray, property) { 
    return objectArray.reduce(function (acc, obj) {
     let key = obj[property]
     if (!acc[key]) {
      acc[key] = {}
      acc[key][property] = key
      acc[key].count = 0
     }
     acc[key].count++
     return acc 
     }, {})
    }
    
const result = groupBy(countries, 'name')
console.log(result)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process of creating a Matlab function that can take a single cell array of strings as input and generate a structure array containing the same strings in alphabetical order?

I need to create a custom function that takes a single cell array of strings and returns a structure array with the same strings in alphabetical order. Additionally, each string must have a 'count' field indicating how many times it appears in th ...

Tips for generating rows with material-ui grid

I am utilizing material-ui grid to make my content responsive. However, I am facing challenges in creating nested rows for my layout. My requirement is to have the first row span the entire width and then divide it into 3 columns with widths of 3, 3, and 6 ...

I'm sorry, but we were unable to locate the module: Error: Unable to find 'fs' in '/usr/src/app/node_modules/jpeg-exif/lib'

Encountering an error when building a react app on production: Module not found: Error: Can't resolve 'fs' in '/usr/src/app/node_modules/jpeg-exif/lib' Node Version: Node version 18 Steps taken in Docker Production: npm install - ...

How come the CSS styles I set for larger screens (1440px) are taking precedence over the ones I set for smaller screens (1280px)?

import styled from "styled-components"; import { devices } from "./devices"; export const HeaderContainer = styled.div` padding: 20px; @media ${devices.lg} { padding: 40px 90px; } @media ${devices.xl} { padding: 40px 2 ...

What is the method for sending parameters to PHP from an HTML file using AJAX?

My protfolio.html file contains a table #gallery with different categories. I want to dynamically update the content of the #gallery based on the selected category using ajax. I have a php file that scans a specific folder for images related to the categor ...

A nested DragSource component within a parent DragSource component in React DnD

In my project, I am working with a tree structure that consists of a root "Tree" component containing a list of root "TreeNodes". Each TreeNode can have an arbitrary number of children. Within the render method of the TreeNode component, I iterate over th ...

The selected option is not visually highlighted in the ui-select due to a programming issue

angular version: AngularJS v1.3.6 http://github.com/angular-ui/ui-select : Version: 0.8.3 var p1 = { name: 'Ramesh', email: '[email protected]', age: 99 }; $scope.people = [ { name: 'Amalie', ...

grouping arrays based on assigned email addresses

I am working on a foreach function that organizes an array of products into separate arrays based on the 'dsid': $products_array = array(); $products_query = tep_db_query("select products_id, products_name, drop_ship_id from " . TABLE_ORDERS_PRO ...

Combine the output from a MySQL column into a comma-separated list using PHP

I have a straightforward question that involves retrieving data from a single column in a database table. The number of rows may vary. SELECT column1 as NUMBER WHERE column1 ... The output would look something like this: NUMBER 1 2 In PHP, I want t ...

Switch ng-model in Angular to something different

I am looking to transform my own tag into a template <div><input .../><strong>text</strong></div> My goal is to have the same values in both inputs. Check out the plunker here If I change the scope from scope: {value:' ...

Designing a dynamic presentation with varying intervals between slides

I am working on a jQuery slideshow that smoothly transitions between different <div> elements. In the current code, the slides change every 5 seconds. Is there a way to modify this so I can specify custom durations for displaying each slide? Here i ...

I am having trouble retrieving the API data. How can I determine if my code is correct or incorrect?

Here is some API data retrieved from a website... date: (...) dateTimeGMT: (...) matchStarted: (...) squad: (...) team-1: (...) team-2: (...) toss_winner_team: (...) type: (...) unique_id: (...) winner_team: (...) When I use console.log(response.date) or ...

Trie-based autocomplete functionality

I am currently creating an auto-completion script and I'm considering utilizing a trie data structure. My main concern is that I want all possible matches to be returned. For instance, when I type in the letter r, I expect to see all entries beginning ...

Expanding file input fields in Javascript

I am facing an issue with my form and file input. I need to select images from a different folder. echo '<pre>'; var_dump($_FILES); echo '</pre>'; Upon submitting the form, only the last selected image is displayed, but I ...

What methods can I employ to intentionally trigger a mongodb error in order to evaluate the try and catch condition using jest?

Testing my code is essential, but I want to ensure that any errors are caught and handled properly. This is achieved by structuring my code in a way that prevents it from reaching the catch condition. This is made possible by using a throw condition for t ...

Tips for maximizing the efficiency of a callback when utilizing the filter function in Primefaces for 'myDataTable'

Currently using Primefaces 5.1, and I've encountered a situation where I want to hide a table until after the filter is applied in Javascript. My initial thought was to simply set the css of the table to visibility:hidden;, followed by running the fol ...

The Art of Checkbox Design

Seeking help in replacing the default check mark on a checkbox with an image. Here is the code snippet I am currently using: <html> <head> <style> .bl { background:-webkit-gradient(linear, left top, left bottom, color-stop(0, #175899), c ...

Error encountered when attempting to invoke a function from a customized header file in C++

For this specific application, I have set up three parallel arrays to store the names of ten account holders, their IDs, and their balances. The structure of my main file is as follows: #include <iostream> #include <iomanip> #include <strin ...

Show a dynamic Swiper carousel upon selecting a thumbnail in an image gallery

I am in the process of creating a thumbnail gallery that includes a slider feature using Swiper. The default setup has the slider hidden, and once an image is clicked, the slider should appear with the selected image. To close the slider and return to the ...

"Encountering difficulties while trying to modify the QuillNoSSRWrapper value within a Reactjs

Currently, I am working on a project involving ReactJS and I have opted to use the Next.js framework. As of now, I am focused on implementing the "update module" (blog update) functionality with the editor component called QuillNoSSRWrapper. The issue I ...