
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Map Array of Object Titles into New Array Based on Property Value in JavaScript
Let’s say, we have an array of objects like this −
const arr = [{ country: "cananda", count: 2 }, { country: "jamaica", count: 2 }, { country: "russia", count: 1 }, { country: "india", count: 3 }, { country: "spain", count: 2 }, { country: "portugal", count: 1 }, { country: "italy", count: 1 }];
We are required to write a function that takes in this array, maps over it and returns an array of strings with country names repeated “count” number of times for each particular object.
Therefore, the output of the function for this object should be −
['canada', 'canada', 'jamaica', 'jamaica', 'russia', 'india', 'india', 'india','spain', 'spain','portugal', 'italy']
Let’s write the code for this function. We will use the Array.prototype.reduce() method here −
Example
const arr = [{ country: "canada", count: 2 }, { country: "jamaica", count: 2 }, { country: "russia", count: 1 }, { country: "india", count: 3 }, { country: "spain", count: 2 }, { country: "portugal", count: 1 }, { country: "italy", count: 1 }]; const repeatCount = (arr) => { return arr.reduce((acc, val) => { let { count, country } = val; while(count--){ acc.push(country); } return acc; }, []); }; console.log(repeatCount(arr));
Output
The output in the console will be −
[ 'canada', 'canada', 'jamaica', 'jamaica', 'russia', 'india', 'india', 'india', 'spain', 'spain', 'portugal', 'italy' ]
Advertisements