Search This Blog

2023/09/11

Javascript:Shortest Words in Array using Reduce

Find shortest words in array.

Code:
const words = [
"cat",
"dog",
"bird",
"elephant",
"lion",
"tiger",
"zebra",
"monkey",
"ox",
"b",
"a",
"giraffe",
"antelop",
];

function findShortestWords(words) {
let wordWithShortestLength = words.reduce((acc, current) => {
if (current.length < acc.length) {
return current;
} else {
return acc;
}
}, words[0]);

let wordsWithShortestLength = words.filter((m)=>{
return m.length == wordWithShortestLength.length
})
return wordsWithShortestLength
}

var shortest = findShortestWords(words);
console.log(shortest);


Output:
[ 'b', 'a' ]

No comments:

Post a Comment