简体   繁体   中英

How to extract certain words from an array?

I have this array that was given to me to use:

const databaseEntry = ['Faction: First Galactic Empire', 'Name: Firms Piett', 'Rank: Admiral'];

And my task is to create a variable from this array that ends up like this

'Firms Piett, Admiral of the First Galactic Empire.'

I have tried and retried, but I'm still new with arrays

Re-organize your data as an object so as to have more simple key-value associations, then build your sentence:

 const foo = entry => { const o = {}; for(let e of entry) { let [key, value] = e.split(': '); o[key]=value; } return `${o.Name}, ${o.Rank} of the ${o.Faction}`; } console.log(foo(['Faction: First Galactic Empire', 'Name: Firms Piett', 'Rank: Admiral']));

Since you're a beginner, you might need to check out String.split and array destructuring to fully understand the code above.

Use String.split() .

Loop through each item in the array, and split on the space. This will get you an array of two values for each item. For example, ["Faction:", "First Galactic Empire"] . Then you can just use the index values to get the strings.

Welcome to StackOverflow :)

 const databaseEntry = ['Faction: First Galactic Empire', 'Name: Firms Piett', 'Rank: Admiral']; let faction = databaseEntry[0].split(": ")[1] let name = databaseEntry[1].split(": ")[1] let rank = databaseEntry[2].split(": ")[1] console.log(`${name}, ${rank} of the ${faction}.`) // Since you asked for the final lenght: console.log(`${name}, ${rank} of the ${faction}.`.length) // => You can add the '.length' attribute to any String ("Hello World".length)

This is an easy solution for your problem. And since you seem to be new to JavaScript this is probably the best thing to do to help you to understand arrays :)

Really simple one-liner with map , split and array destructuring.

 const databaseEntry = ['Faction: First Galactic Empire', 'Name: Firms Piett', 'Rank: Admiral']; const [faction, name, rank] = databaseEntry.map(e => e.split(": ")[1]); console.log(`${name}, ${rank} of the ${faction}`);

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