Michael Shtefanitsa
Michael Shtefanitsa

Reputation: 303

Find the shortest string in array

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

Upvotes: 9

Views: 34306

Answers (6)

Tobiloba Oluwadare
Tobiloba Oluwadare

Reputation: 21

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

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

Upvotes: 2

Ori Drori
Ori Drori

Reputation: 191946

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

Upvotes: 15

pz_stackoverflow
pz_stackoverflow

Reputation: 119

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

Upvotes: -4

Nina Scholz
Nina Scholz

Reputation: 386550

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

Upvotes: 1

synthet1c
synthet1c

Reputation: 6282

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

Upvotes: 5

Pranav C Balan
Pranav C Balan

Reputation: 115212

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

Upvotes: 30

Related Questions