Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
July 13, 2022 03:11 am GMT

Basic Array Methods

I have always had interest in data structures ever since I started going to school for Computer Science, but one thing that I could never remember were array methods. Hopefully, you're like me and want to refer back to a simple documentation explaining how array methods work!

1. shift()

The shift method allows us, as the user to remove the first element from an array, returns the first element and modifies the original array.

let videoGames = ['Minecraft', 'Among Us', 'Valoran't, 'GTA']videoGames.shift() // returns Minecraftconsole.log(videoGames) // ['Among Us', 'Valorant', 'GTA']

2. pop()

The pop method acts in the same way as shift, the only difference being is that it removes the last element of any array.

let sports = ['basketball', 'baseball', 'football', 'soccer']sports.pop() //returns soccerconsole.log(sports) // ['basketball', 'baseball', 'football']

3. splice()

The splice method has the ability to add or remove elements from an array. The first argument is the index location where the elements are to be removed or added. The second argument is the number of elements that you want to remove from the array.

let avengers = ['Hawkeye', 'Thor', 'Spider-Man', 'Hulk', 'Iron Man', 'Captain America']avengers.splice(1,3) // returns ['Thor', 'Spider-Man', 'Hulk']console.log(avengers) // ['Hawkeye', 'Iron Man', 'Captain America']

Now if we wanted to remove an index, and add a different value you it would look like this.

let avengers = ['Hawkeye', 'Thor', 'Spider-Man', 'Hulk', 'Iron Man', 'Captain America']avengers.splice( 1,1, 'Ant-Man') // returns Thor and replaces Thor with Ant-Manconsole.log(avengers) // ['Hawkeye', 'Ant-Man', 'Spider-Man', 'Hulk', 'Iron Man', 'Captain America']

4.) slice()

This slice method is used to remove elements from an array without modifying the original array. Also with this method, with what elements you do remove a brand new array is created with those elements. When specifying the range of elements that you want to remove just like our other methods you first want to define was element you want to start with, and the second argument is what you want to end with (the ending index is not included in the new array).

let codeLanguages = ['Python', 'JavaScript', 'Java', 'TypeScript', C++]codLanguages.slice(1,3) // returns ['JavaScript', 'Java'] and creates a new arrayconsole.log(codeLanguages) // ['Python', 'JavaScript', 'Java', 'TypeScript', C++]

Original Link: https://dev.to/millsy64/basic-array-methods-2d97

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To