0

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);

1 Answer 1

3

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);

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

1 Comment

That's exactly ! The alternative option is better

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.