9

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
  • 1
    you could sort by length. Commented Nov 29, 2016 at 11:35

6 Answers 6

31

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)
)

Sign up to request clarification or add additional context in comments.

Comments

16

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(o => o.length));
console.log(min);

2 Comments

But you don't find the shortest string. You find the shortest string's length.. Despite OP has accepted your answer i believe the answer still remains unsolved.
The problem is in the phrasing of the question. Look at the op's code.
5

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)
)

Comments

2

var arr = ["aaaa", "aa", "aa", "aaaaa", "a", "aaaaaaaa"];

console.log(
  arr.reduce(function(a, b) {
    return a.length <= b.length ? a : b;
  })
)

Comments

1

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));

Comments

-4

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 Comment

Sort sorts on alphabet. Not on string length. The output there will be "cats" not "ice".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.