Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the largest string in an array of strings [duplicate]

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'];
like image 409
K.Wagner Avatar asked Dec 07 '25 04:12

K.Wagner


1 Answers

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));
like image 59
Mohammad Usman Avatar answered Dec 08 '25 18:12

Mohammad Usman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!