Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
map() array of object titles into a new array based on other property value JavaScript
Let's say, we have an array of objects like this ?
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
}];
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']
Using Array.reduce() Method
We'll use the Array.prototype.reduce() method to iterate through each object and repeat country names based on their count values:
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));
[ 'canada', 'canada', 'jamaica', 'jamaica', 'russia', 'india', 'india', 'india', 'spain', 'spain', 'portugal', 'italy' ]
Using Array.flatMap() Method
Alternatively, we can use Array.flatMap() with Array.fill() for a more modern approach:
const arr = [{
country: "canada",
count: 2
}, {
country: "jamaica",
count: 2
}, {
country: "russia",
count: 1
}, {
country: "india",
count: 3
}];
const repeatCountFlatMap = (arr) => {
return arr.flatMap(obj => Array(obj.count).fill(obj.country));
};
console.log(repeatCountFlatMap(arr));
['canada', 'canada', 'jamaica', 'jamaica', 'russia', 'india', 'india', 'india']
How It Works
The reduce() method builds an accumulator array by iterating through each object. For each object, it extracts the country and count properties using destructuring, then uses a while loop to push the country name into the accumulator array the specified number of times.
The flatMap() approach creates an array of the required length using Array(count) and fills it with the country name, then flattens all sub-arrays into a single array.
Conclusion
Both methods effectively transform an array of objects into a flattened array where each country appears the number of times specified by its count property. The reduce() method offers more control, while flatMap() provides a more concise solution.
