Robert Hung
Robert Hung

Reputation: 165

JavaScript - Array mapping with another array

I have two arrays which starts off as this:

let days = [null, null, null, null, null, null, null];

const weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']

Depending on what data I'm given, I want to map a new array with the corresponding weekday, but still keep it the same size array.

let numDays = ["0","2","4"]

let days = days.map(?)

days
> ['Sunday', null, 'Tuesday', null, 'Thursday', null, null]

I have attempted a conversion function which can convert numDays to its correspondingweekdays

const convert = function (c) {
  return weekdays[c];
}

numDays.map(convert)
> ['Sunday', 'Tuesday', 'Thursday']

But not sure how to retain the array size for the result I need.

Cheers!

Upvotes: 0

Views: 1503

Answers (2)

kevguy
kevguy

Reputation: 4438

I don't think you need the days variable to be [null, null, null, null, null, null, null].

const weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

let numDays = ["0","2","4"];

var days = weekdays.map(function(day, index){
  if (numDays.indexOf(index.toString()) >= 0){
    return day;
  } else {
    return null;
  }
});

console.log(days);

Upvotes: 2

dtkaias
dtkaias

Reputation: 781

This approach might be easier than using map, you can use forEach to loop over the required indexes, look up the day and add them to your days array as required.

const weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
let numDays = ["0","2","4"]
let days = [null, null, null, null, null, null, null];
numDays.forEach(i=>days[i] = weekdays[i]);
console.log(days);

Upvotes: 2

Related Questions