I'm trying to solve the below. I don't have much practical knowledge of javascript.
I need to find the largest string given from an array. If multiple strings in the array have the same length, return the first one of the longest length.
let test13 = ['a', 'aa', 'aaa'];
let test14 = ['asdf', 'qwer', 'zxcv'];
let test15 = ['asdfasdf fdasdf a sd f', ' asdfsdf', 'asdfasdfds', 'asdfsdf', 'asdfsdaf'];
let test16 = ['ddd','dddddddd','dddd','ddddd','ddd','dd','d','d','dddddddddddd'];
You can use .reduce() method to find the desired string by checking the length of each string in array and returning the one having more characters:
let test1 = ['a', 'aa', 'aaa'];
let test2 = ['asdf', 'qwer', 'zxcv'];
let test3 = ['asdfasdf fdasdf a sd f', ' asdfsdf', 'asdfasdfds', 'asdfsdf', 'asdfsdaf'];
let test4 = ['ddd','dddddddd','dddd','ddddd','ddd','dd','d','d','dddddddddddd'];
let reducer = (arr) => arr.reduce((r, c) => r.length >= c.length ? r : c);
console.log(reducer(test1));
console.log(reducer(test2));
console.log(reducer(test3));
console.log(reducer(test4));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With