Mike Alexander Mike Alexander -3 years ago 101
Javascript Question

Trying to Find String in Array of Arrays Based on Index of Corresponding Array

I've got an array of names:

names = [name1, name2, name3...]


that corresponds to an array of arrays that contain quotes which correspond to the array of names.

quotes = [[q#1a, q#2b..], [q#1c, q#2d..], [q#1e, q#2f]]


I'm trying to create a function where you can enter a specific quote (ex.
q#1c
) and console.log will return the name of the person that said it.

I'm stuck and keep getting undefined. Any suggestions? Below is what I have so far.

function findQuote(quote) {
return quote == `"q#1c"`;
}

let whoSaidIt = (c) => {
let quote = quotes.index;
return `${name[c]} said ${quotes[c]}.`;
};

console.log(whoSaidIt(quotes.findIndex(findQuote)));

Answer Source
let names = ['name1', 'name2', 'name3'];
let quotes = [['q#1a', 'q#2b'], ['q#1c', 'q#2d'], ['q#1e', 'q#2f']];
let whoSaidIt = (c) => quotes.reduce((a, v, i) => quotes[i].includes(c) ? `${names[i]} said ${c}.` : a, '') || 'No-one said that!';

whoSaidIt('q#1c'); //Returns 'name2'

Assuming names.length === quotes.length and names[I] said quotes[I], you can use reduce to get your answer. a is '' by default, which is determined by the second attribute.

We simply set the return message when we find the quote. i can be used on names to get the person who said the quote. If no match is found, we can leave a default message using ||.

You may want to consider using an object to store both names and quotes as it may be easier to refer to. { 'q#1a': 'name1', ... }

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download