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: "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'
]
Updated on: 2020-08-25T06:44:54+05:30

232 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements