user9796514
user9796514

Reputation: 11

How to slice value out of array in JS

I am trying to isolate the first value from an array that is constructed like below using JS:

[john,mike,tom]

I have tried the slice method but it is not working and I am assuming it's the way the array is constructed where the strings aren't enclosed in quotes. What would be the best way to transform the array above to either a string as a whole or a more properly formatted array so I can pull out any value I want?

edit For additional context, the array I mentioned above is the way is being passed to me from the source. I am trying to figure out how I can work with it to be able to slice up the values.

Sorry for the layman presentation of my question but I am still quite the beginner in JS and would appreciate it if anyone could help me out. Thanks!

Upvotes: 1

Views: 1246

Answers (3)

Michael W. Czechowski
Michael W. Czechowski

Reputation: 3457

You can use the array prototype .shift(), but it will mutate your original array.

const john = {x: 124};
const mike = {x: 333};
const tom = {y: 355};

const slicy = [john, mike, tom].shift();

console.log(slicy);

Upvotes: 0

Michelle Colin
Michelle Colin

Reputation: 79

Why do you need the strings to not have quotes? Is there an specific reason?

In js you need to put quotes on strings. If you try for example declaring an array in the way you did above the following will happen:

let x = [janaina,joao,julia]

VM203:1 Uncaught ReferenceError: janaina is not defined at :1:10

So, correct way to delcare your array:

let x = ['janaina','joao','julia']

Now slice will work:

x.slice(0,1);

The result will be:

['janaina']

Upvotes: 0

Zohaib Ijaz
Zohaib Ijaz

Reputation: 22875

In javascript, strings are enclosed in quotes. e.g.

'john', "mike" ect. so in order to create an array/list you need to put these values with quotes inside array and then access using index e.g.

var array = ['john', 'mike', 'tom']
console.log(array[0]); // john

Upvotes: 4

Related Questions