1

I have list of arrays with different length. I want to find the highest length of the array in the list and make all remaining arrays of same length by filling null/empty value.

e.g: I have a list of array

[ [1,2,2,4,4], [2,3,2,4], [2,4,21,4], [1,2]];

I want to find the highest length of array in the list i.e 5 in above case ( length of [1,2,2,4,4])

I want to make all remaining arrays also of same length like below

[ [1,2,2,4,4], [2,3,2,4,''], [2,4,21,4,''], [1,2,'','','']];

How can I achieve that?

Sample code of list of array and finding max length

let data = [ [1,2,2,4,4],
[2,3,2,4], [2,4,21,4], [1,2]
];

const length = Math.max(...(data.map(el => el.length)));

console.log('array list', data);
console.log('max length', length);

3 Answers 3

3

You could iterate the array and push empty strings until the wanted length.

const
    data = [[1, 2, 2, 4, 4], [2, 3, 2, 4], [2, 4, 21, 4], [1, 2]],
    length = Math.max(...data.map(({ length }) => length));

data.forEach(a => {
    while (a.length < length) a.push('');
});

console.log('max length', length);
console.log('array list', data);

If you like to get a new array, you could map new arrays.

const
    data = [[1, 2, 2, 4, 4], [2, 3, 2, 4], [2, 4, 21, 4], [1, 2]],
    length = Math.max(...data.map(({ length }) => length)),
    result = data.map(a => Array.from({ length }, (_, i) => i < a.length ? a[i] : ''));

console.log('max length', length);
console.log('array list', result);

Sign up to request clarification or add additional context in comments.

Comments

2

You can concat an array filled with null values to each entry in data:

let data = [ [1,2,2,4,4],
[2,3,2,4], [2,4,21,4], [1,2]
];

const length = Math.max(...(data.map(el => el.length)));

data = data.map(a => a.concat(new Array(length - a.length).fill(null)));

console.log('array list', data);
console.log('max length', length);

Comments

2

let data = [ [1,2,2,4,4],
[2,3,2,4], [2,4,21,4], [1,2]
];

const length = Math.max(...(data.map(el => el.length)));

data.forEach(item => {
    while (item.length < length){
        item.push(''); 
    }
})

console.log(data)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.