Don't Understand Concept

Viewed 29

Given the below array, create a function which loops through each name, comparing the length of each to determine the longest name, save that name to the variable longest_name. Return longest_name to the another variable called answer and log the answer variable to the screen.

let array = [ "John", "Lee", "Smitty", "Cyren", "Linda", "Bart", "Jason", "Wilson", "Travis", "Newt"];

would it be something like this

let array = [ "John", "Lee", "Smitty", "Cyren", "Linda", "Bart", "Jason", "Wilson", "Travis", "Newt"];

let result = array.filter(val =>includes(val));

console.log(result);

2 Answers

Here is a sample implementation.

// A function which accepts an array as input
function findLongest(names) {
  let longest_name = '';
  // Loop through all the names
  for (let i = 0; i < names.length; i += 1) {
    // If the names is longer than longest_name, update it
    if (names[i].length > longest_name.length) {
      longest_name = names[i];
    }
  }
  return longest_name;
}

let array = [ "John", "Lee", "Smitty", "Cyren", "Linda", "Bart", "Jason", "Wilson", "Travis", "Newt"];

let answer = findLongest(array);

console.log(answer)

Simply use reduce on the array and return the longest element every time.

The longest variable will contain the last longest element.

Do run the snippet and understand how reduce, ? : (Elvis operator) works in javascript

let array = [ "John", "Lee", "Smitty", "Cyren", "Linda", "Bart", "Jason", "Wilson", "Travis", "Newt"];
let longest = array.reduce((prev, curr) => curr.length > prev.length ? curr : prev,'');
console.log(longest)

Hope this helps

Related