Lisa123456
Lisa123456

Reputation: 63

Return a word in an array

I have an array of various words in which I want to check the first word found in this string from the array of words.

const arrayOfWord=['@Robot','@Human','@Animal','@Hero']
const body = 'This is a try to found the @Human & the @Animal'

arrayOfWord.some(arrayOfWord=> body.includes(arrayOfWord)) // This will return true 
// i want to get the value @Human as it's the first word in the string that exists in the array

I want to get value = '@Human'. How can I achieve this?

Upvotes: 3

Views: 726

Answers (5)

Nick Parsons
Nick Parsons

Reputation: 50759

You could map your array of words to an array of indexes of where each word appears in the string. Then you can use .reduce() to find the minimum value number in the array which are not -1.

See example below:

const arrayOfWord = ['@Robot','@Human','@Animal','@Hero'];
const body = 'This is a try to found the @Human & the @Animal';

const arrayOfIdx = arrayOfWord.map(wrd => body.indexOf(wrd))
const minItemIdx = arrayOfIdx.reduce((min, idx, i) => 
  idx === -1 || (arrayOfIdx[min] !== -1 && arrayOfIdx[min] < idx) ? min : i, 0);

const res = arrayOfWord[minItemIdx];
console.log(res);

Upvotes: 0

Karine Liuti
Karine Liuti

Reputation: 71

Lisa! Maybe it can help you...

const arrayOfWord=['@Robot','@Human','@Animal','@Hero']
const body = 'This is a try to found the @Human & the @Animal'

// Get the @Human index
indexOfHuman = arrayOfWord.indexOf('@Human')

//This line will get the value of @Human
valueOfHuman = arrayOfWord[indexOfHuman]

Upvotes: 0

Lajos Arpad
Lajos Arpad

Reputation: 76591

As your example shows there could be multiple words occuring in the text and we are searching for the earliest. Please take a look at the code below:

const arrayOfWord=['@Robot','@Human','@Animal','@Hero']
const body = 'This is a try to found the @Human & the @Animal'

var output = undefined;
arrayOfWord.filter((arrayOfWord)=> {
    let retVal = ((body.indexOf(arrayOfWord) >= 0) ? body.indexOf(arrayOfWord) : false);
    if (retVal !== false) {
        if ((!output) || (output.index > retVal)) output = {index : retVal, word: arrayOfWord};
    }
    return retVal !== false;
})
console.log(output ? output.word : undefined);

Upvotes: 0

Janie
Janie

Reputation: 646

Try using .find() instead of .some()

The .find() method returns the value of the first element in the provided array that satisfies the provided testing function.

const arrayOfWord=['@Robot','@Human','@Animal','@Hero']
const body = 'This is a try to found the @Human & the @Animal'

const res = arrayOfWord.find(arrayOfWord => body.includes(arrayOfWord))
console.log(res)

Upvotes: 2

M. Twarog
M. Twarog

Reputation: 2623

You can try to split body into array and then filter out all words that aren't in arrayOfWord. After such transformation you can pick up first element.

body.split(" ").filter(word => arrayOfWord.includes(word))[0]

Upvotes: 0

Related Questions