본문 바로가기
알고리즘/Codewars

[Codewars] Coding Meetup #5 - Higher-Order Functions Series - Prepare the count of languages (7 kyu) / JavaScript

by fluss 2023. 5. 4.

https://www.codewars.com/kata/5828713ed04efde70e000346

 

Codewars - Achieve mastery through coding practice and developer mentorship

A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

DESCRIPTION:

You will be given an array of objects (associative arrays in PHP, table in COBOL) representing data about developers who have signed up to attend the next coding meetup that you are organising.

Your task is to return an object (associative array in PHP, table in COBOL) which includes the count of each coding language represented at the meetup.

For example, given the following input array:

var list1 = [
  { firstName: 'Noah', lastName: 'M.', country: 'Switzerland', continent: 'Europe', age: 19, language: 'C' },
  { firstName: 'Anna', lastName: 'R.', country: 'Liechtenstein', continent: 'Europe', age: 52, language: 'JavaScript' },
  { firstName: 'Ramon', lastName: 'R.', country: 'Paraguay', continent: 'Americas', age: 29, language: 'Ruby' },
  { firstName: 'George', lastName: 'B.', country: 'England', continent: 'Europe', age: 81, language: 'C' },
];

your function should return the following object (associative array in PHP, table in COBOL):

{ C: 2, JavaScript: 1, Ruby: 1 }

Notes:

  • The order of the languages in the object does not matter.
  • The count value should be a valid number.
  • The input array will always be valid and formatted as in the example above.




This kata is part of the Coding Meetup series which includes a number of short and easy to follow katas which have been designed to allow mastering the use of higher-order functions. In JavaScript this includes methods like: forEach, filter, map, reduce, some, every, find, findIndex. Other approaches to solving the katas are of course possible.

 

코드

function countLanguages(list) {
  const map = new Map();
  for(let i = 0; i < list.length; i++){
    if(map.has(list[i].language)){
      map.set(list[i].language, map.get(list[i].language) + 1);
    } else{
      map.set(list[i].language, 1);
    }
  }
  return Object.fromEntries(map);
}

댓글