Robert Hung
Robert Hung

Reputation: 165

JavaScript - Create a new array with missing elements rather than re-mapping with undefined

When selecting check boxes, I create an array with its corresponding value / index using the below line.

days[dayCronValue] = dayString;

If I select Thursday, output is as follows.

days
> [ , , , , 'Thursday']

If I select Saturday, output is as follows.

days
> [ , , , , 'Thursday', , 'Saturday']

This works perfectly as what gets saved is not the string, but its index.

'0 0 0 * * 4,6'

The problem I have is that my method to remove the days when unchecked cannot replace the existing element with a 'missing' element. I use the map method to replace it with undefined. My thought process below.

days
> [ , , , , 'Thursday', , 'Saturday']

days[0]
> undefined

days = days.map(day => day === dayString ? undefined : day);

Eg. If I uncheck Thursday, output is as follows.

days
> [ , , , , undefined, , 'Saturday']

The cronString which gets saved is still the same, as undefined still represents an existing index.

'0 0 0 * * 4,6'

My logic thinks I should just do a forEach method to iterate over days for any typeof day !== 'undefined' and use the days[dayCronValue] = dayString to build a new array. This way, it creates a new array with the correct indexes and correct elements.

I just can't figure out how to do that (or if I'm just over-complicating this process).

Cheers!

Upvotes: 0

Views: 316

Answers (2)

Bergi
Bergi

Reputation: 665130

You can use

var daystring = days.filter(day => day !== undefined).map((_, i) => i).join(',');

and don't need to care whether the properties don't exist of just don't contain a value. Notice that using delete on arrays, and using sparse arrays in general, is pretty bad for performance.

Upvotes: 0

PMV
PMV

Reputation: 2138

If the goal here is to create a sparse array (where only a few particular indices are defined), then the answer is just to use delete days[4] to delete the day at index 4.

Upvotes: 3

Related Questions