map() array of object titles into a new array based on other property value JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

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'
]
raja
Published on 25-Aug-2020 06:44:14
Advertisements