Qwerpotify
Qwerpotify

Reputation: 49

Can we slice string in array

I have an array like below

array_object = [video1.mp4 , video2.mp4 , video3.mp4];

I like to remove the .mp4 from the array so i used

array = array_object.slice(0,-4);

but it not working cause the string is in array. are there anyway to delete the .mp4 even it inside the array.

Upvotes: 2

Views: 72

Answers (2)

Willem van der Veen
Willem van der Veen

Reputation: 36580

As get of my lawn said use array.map. Array.map gets as an argument a callback function which gets executed on every element of the array. Then a new array is returned. For example:

const array_object = ['video1.mp4', 'video2.mp4', 'video3.mp4'];

const new_array = array_object.map(item => item.slice(0, -4));

console.log(array_object === new_array); // logs false a new array is returned;

The function which is passed in map gets every array index as an argument:

item => item.slice(0, -4)

Then on every element the function is performed and put in the index of the new array.

Upvotes: 1

Get Off My Lawn
Get Off My Lawn

Reputation: 36299

You need to loop over the items. This can be done with an array map.

const array_object = ['video1.mp4', 'video2.mp4', 'video3.mp4'];

const new_array = array_object.map(item => item.slice(0, -4));

console.log(new_array);

Upvotes: 3

Related Questions