Velvet Star Monitor

Standout celebrity highlights with iconic style.

general

Find the shortest string in array

Writer Matthew Harrington

How can i find the shortest string in javascript array with different count of array elements? I used

var min = Math.min(arr[0].length,arr[1].length,arr[2].length);

and i have result like shortest string between 3 elements of array. But I don't want to care about numbers of elements

1

5 Answers

Use Array#reduce method.

var arr = ["aaaa", "aa", "aa", "aaaaa", "a", "aaaaaaaa"];
console.log( arr.reduce(function(a, b) { return a.length <= b.length ? a : b; })
)

With ES6 arrow function

var arr = ["aaaa", "aa", "aa", "aaaaa", "a", "aaaaaaaa"];
console.log( arr.reduce((a, b) => a.length <= b.length ? a : b)
)
0

Use Array#map to create an array of lengths, and then apply it to Math.min():

var arr = ['cats', 'giants', 'daughters', 'ice'];
var min = Math.min.apply(Math, arr.map(function(str) { return str.length; }));
console.log(min);

Or use ES6's array spread and arrow function:

var arr = ['cats', 'giants', 'daughters', 'ice'];
var min = Math.min(...arr.map(({ length }) => length));
console.log(min);
2

You could use Array.prototype.reduce

const arr = ['small', 'big', 'yuge']
const shorter = (left, right) => left.length <= right.length ? left : right
console.log( arr.reduce(shorter)
)
0

You could use Math.min with Array#reduce.

var arr = ["aaaa", "aa", "aa", "aaaaa", "a", "aaaaaaaa"];
console.log( arr.reduce(function(r, a) { return Math.min(r, a.length); }, Infinity)
);

ES6

var arr = ["aaaa", "aa", "aa", "aaaaa", "a", "aaaaaaaa"];
console.log(arr.reduce((r, a) => Math.min(r, a.length), Infinity));

Please see this short solution below. I hope it helps:

var arr = ['cats', 'giants', 'daughters', 'ice'];
arr.sort(); // ice, cats, giants, daughters
var shortest_element = arr[0]; // ice
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy