Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map an array to set empty elements

Given:

let input = [0, 1, 2,,,,,7]

I want to get:

let output = [, 1, 22, 333, 4444, 55555, 666666, 7777777]

(i.e. value equal key times the key)

How can I map (or equivalent) input including empty values?
If I do input.map() I will get [, 1, 22,,,,,7777777] because map will -of course- not iterate empty values. Data can be arbitrary, strings, objects, numbers, etc. Using numbers in this example for simplicity.

like image 470
adelriosantiago Avatar asked May 01 '26 06:05

adelriosantiago


2 Answers

You can fill the array before applying a mapping function so that all indexes are iterated over, including empty ones.

let result = input.fill().map((_,index)=>{/*...*/});

The mapping function provided as the second argument to Array.from can be similarly used.

let result = Array.from({length: input.length}, (_, index)=>{/*...*/});

Spread syntax does not ignore empty slots, so we can create a copy of the array with spread syntax and map over that. This has an added advantage of having the elements at each index available as well.

let result = [...input].map((elem, idx)=>{/*...*/});
like image 148
Unmitigated Avatar answered May 03 '26 21:05

Unmitigated


map() can't include empty values. w3schools

map() does not execute the function for array elements without values.

So, either iterate the array with a for-loop:

out = [];
for (var i = 0; i < input.length; i++) {
    var item = input[i];
    if (item != null)
        out[i] = item.toString().repeat(item);
}

Or create another mapx() functor:

Array.prototype.mapx = function(fn) {
    var out = [];
    for (var i = 0; i < this.length; i++) {
        var item = this[i];
        // if (item == null) item = sherlockHolmesKnow();
        out[i] = fn(item, i);
    }
    return out;
};

and apply on the input:

input.mapx( (val, index) => (val == null ? null : (val+'').repeat(val)) )

which yields ["", "1", "22", null, null, null, null, "7777777"].

Let's skip the AI part of clever guessing the numbers in the empty slots.

like image 37
Xiè Jìléi Avatar answered May 03 '26 19:05

Xiè Jìléi