Javascript remove empty items from sides of an array

This is exactly what I mean but in Javascript: PHP remove empty items from sides of an array

I'm looking around the cleanest way to do it. I wondering if there is a better way than loop the array manually.

Here an example:

const fullArray = new Array(10);
fullArray[3] = 1;
fullArray[5] = 1;
fullArray[7] = 1;
console.log('Input:', fullArray);

const trimedArray = new Array(4);
trimedArray[0] = 1;
trimedArray[2] = 1;
trimedArray[4] = 1;
console.log('Output:', trimedArray);

Upvotes: 0

Views: 58

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370779

If you take the keys of the array (which takes only properties that exist on the array - it won't take sparse indicies like 0 to 2, or 4, or 6, or 8 in your example), you can call Math.min and Math.max on them:

const fullArray = new Array(10);
fullArray[3] = 1;
fullArray[5] = 1;
fullArray[7] = 1;

const keys = Object.keys(fullArray);
const min = Math.min(...keys);
const max = Math.max(...keys);
const result = fullArray.slice(min, max + 1);
console.log(result);

Another option, by taking just the ends of the keys array:

const fullArray = new Array(10);
fullArray[3] = 1;
fullArray[5] = 1;
fullArray[7] = 1;

const keys = Object.keys(fullArray);
const min = keys[0];
const max = keys[keys.length - 1];
const result = fullArray.slice(min, Number(max) + 1);
console.log(result);

Upvotes: 3

Related Questions