简体   繁体   中英

How can I return the first item in an array using a arrow function?

I have a challenge where I am supposed to return the first item of an array using an arrow function and I can't get it to work.

Array:

var names = ['Bryan', 'Jeremy', 'Joe', 'Megan', 'Ian', 'Taylor'];

My arrow function:

var first = names.filter((name) => name[0]);

One of the simplest ways to accomplish this is using:

var names = ['Bryan', 'Jeremy', 'Joe', 'Megan', 'Ian', 'Taylor'];
let first = names => names[0];
console.log(first(names));

I think this is what you are looking for.

 var names = ['Bryan', 'Jeremy', 'Joe', 'Megan', 'Ian', 'Taylor']; var first = () => names[0]; console.log(first()); 

Try .find instead of .filter

var first = names.find((name, index) => index === 0);

.filter is often used to get values from an array with a specific condition

You could use Array#find and return true in the callback for the first element.

 var names = ['Bryan', 'Jeremy', 'Joe', 'Megan', 'Ian', 'Taylor'], first = names.find(_ => true); console.log(first); 

An arrow function is really quite superfluous here, but this would be one possible approach:

 var names = ['Bryan', 'Jeremy', 'Joe', 'Megan', 'Ian', 'Taylor']; var first = names.find((name, index) => index === 0); console.log(first); // "Bryan" 

How about a simple function like this, which accepts an array as an argument and returns the first item:

const firstItem = arr => arr.shift();

Then just pass an array to your function:

const first = firstItem(names);

Have a look at below code.

  var names = ['Bryan', 'Jeremy', 'Joe', 'Megan', 'Ian', 'Taylor']; var n = names.filter((names,i)=>names[-i])[0]; console.log(n) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM