Sunday, May 21, 2023
HomeSoftware EngineeringEasy methods to Take away an Aspect from an Array in Javascript

Easy methods to Take away an Aspect from an Array in Javascript


If it is advisable to take away a component from an array in Javascript, then you should utilize one of many following 5 (5) choices:

Choice 1 – Use splice to take away a component

Instance 1 utilizing splice:

var colours = ["red","blue","car","green"];
var carIndex = colours.indexOf("automobile");
colours.splice(carIndex, 1);

// colours = ["red","blue","green"]

Instance 2 utilizing splice:

var myArray = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

// Take away Sunday -- index 0 and Monday -- index 1
myArray.splice(0,2)

Choice 2 – Use filter to take away a component

var myArray = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
let itemToBeRemoved = ["Sunday", "Monday"]
var filteredArray = myArray.filter(merchandise => !itemToBeRemoved.contains(merchandise))

Choice 3 – Use pop to take away a component

let dailyActivities = ['work', 'eat', 'sleep', 'exercise'];

// take away the final ingredient
dailyActivities.pop();
console.log(dailyActivities); // ['work', 'eat', 'sleep']

// take away the final ingredient from ['work', 'eat', 'sleep']
const removedElement = dailyActivities.pop();

// get eliminated ingredient
console.log(removedElement); // 'sleep'
console.log(dailyActivities);  // ['work', 'eat']

Choice 4 – Use take away to take away a component

array.take away(quantity);

Choice 5 – Change size to take away components

var arr = [1, 2, 3, 4, 5, 6];

arr.size = 4;

// [1, 2, 3, 4]
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments