×

Index

JavaScript Tutorial

JavaScript Examples

CSS Tutorial

CSS Examples

JavaScript - Shortening an array

By IncludeHelp Last updated : January 20, 2024

Problem statement

Given an array, write a JavaScript code to shorten the given array.

Let's suppose, you have an array of length greater than 5, shorten it to the length 5.

Shortening an array

For shortening an array, use the Array.length property, check whether the length of an array is greater than 5 using the if condition, if it is greater than 5 then assign the 5 to Array.length property.

JavaScript code for shortening an array

This example will shorten the array (arr) to a length of 5 if the current length is greater than 5.

// declaring an array
const arr = [10, 20, 30, 40, 50, 60, 70];

// print array and length before shortening
console.log("Before shortening.");
console.log(arr);
console.log(arr.length);

// shortening array to 5 elements
if (arr.length > 5) {
  arr.length = 5;
}

// print array and length before shortening
console.log("After shortening.");
console.log(arr);
console.log(arr.length);

// trying to get extra element
console.log(arr[5]); // this will print undefined

Output

The output of the above code is:

Before shortening.
[10, 20, 30, 40, 50, 60, 70]
7
After shortening.
[10, 20, 30, 40, 50]
5
undefined

To understand the above example, you should have the basic knowledge of the following JavaScript topics:

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.