let secretMessage = ['Learning', 'is', 'not', 'about', 'what', 'you', 'get', 'easily', 'the', 'first', 'time,', 'it', 'is', 'about', 'what', 'you', 'can', 'figure', 'out.', '-2015,', 'Chris', 'Pine,', 'Learn', 'JavaScript'];
console.log(secretMessage.indexOf('get','easily')
Why does it only log the value of the 'get', not of both 'get' and 'easily', and how can I return both?
Appreciate the help, I am a beginner, sorry if the formatting is bad.
You can map indexOf over the list of values whose indices are wanted:
let secretMessage = ['Learning', 'is', 'not', 'about', 'what', 'you', 'get', 'easily', 'the', 'first', 'time,', 'it', 'is', 'about', 'what', 'you', 'can', 'figure', 'out.', '-2015,', 'Chris', 'Pine,', 'Learn', 'JavaScript'];
console.log(['get', 'easily'].map(x => secretMessage.indexOf(x)));
The .indexOf() function syntax is as follows indexOf(searchElement, fromIndex) so what that means in your case is its searching for "get" starting from "easily" in the array.
To search both you can try this
console.log(secretMessage.indexOf('get'));
console.log(secretMessage.indexOf('easily'));
and if you need them together you can assign each to a variable then display them together later something like this
let one = secretMessage.indexOf('get');
let two = secretMessage.indexOf('easily');
let result = one + "," + two
console.log(result);
indexOf is a JavaScript array method that only can look for one element at a time, whatever value is being searched for in the array.
A more flexible array method for returning the indices of what you're looking for would be reduce, which lets you return whatever value you want after iterating, including another array with the indices of the values that match your search.
let secretMessage = ['Learning', 'is', 'not', 'about', 'what', 'you', 'get', 'easily', 'the', 'first', 'time,', 'it', 'is', 'about', 'what', 'you', 'can', 'figure', 'out.', '-2015,', 'Chris', 'Pine,', 'Learn', 'JavaScript'];
const matchingIndices = secretMessage.reduce((results, currentValue, currentIndex)=> {
if (currentValue === 'get' || currentValue === 'easily'){
results.push(currentIndex)
}
return results;
}, [])
console.log(matchingIndices) // => [6, 7]