Home > Net >  Obtain All the array name that are tiny from a JavaScript array
Obtain All the array name that are tiny from a JavaScript array

Time:08-08

I Have an array name friends. I want to print all the (not single) name which are tiny from this array. How i can solve it??:

function tinyFriend(friends) {
    let tinyFriend = friends[0]
    for (let i = 0; i < friends.length; i  ) {
        let element = friends[i]
        if (tinyFriend.length>element.length) {
            tinyFriend = element
           }

    }
    console.log("The Smallest Name is",tinyFriend)
}

let friends = ["kamal","shak","shak","shakib", "brac"]
tinyFriend(friends)

my expected result is shak,shak,brac

CodePudding user response:

you basically need to make tinyFriend an array, and add some logic like:

  • is the current name the same length as the one being checked? if so add it to the array
  • is the checked name smaller than the current name(s)? in that case overwrite the array

function tinyFriend(friends) {
    // put the first name in an array to begin..
    let tinyFriends = [friends[0]];
    
    // loop the names in the array
    for (let i = 0; i < friends.length; i  ) {
        let element = friends[i]
        
        // check if same length and add to array if so
        // notice we now check against the first item in the tinyFriends array
        if (tinyFriends[0].length === element.length) {
          tinyFriends.push(element);
        
        // else if the checked name is shorter, replace the array 
        } else if (element.length < tinyFriends[0].length) {
          tinyFriends  = [element];
        }
    }
    
    // remember, since we now output an array, we might need to handle it differently
    console.log("The Smallest Name is", tinyFriends)
}

let friends = ["kamal","shak","shak","shakib", "brac"]
tinyFriend(friends)

CodePudding user response:

You need to be able to store the names somewhere that match the critera - ie in an array.

But it might be easier to find the minimum name length first and then filter out the names whose length match that value.

function tinyFriend(friends) {

  // `map` over the array and return an array of name lengths
  // then use `Math.min` to determine the smallest value
  // in that array. `Math.min` expects a list of arguments
  // so we use the spread syntax on the array
  const min = Math.min(...friends.map(name => name.length));

  // Now `filter` out the names whose length matches that value
  return friends.filter(name => name.length === min);

}

let friends = ['kamal', 'shak', 'shak', 'shakib', 'brac'];
console.log(tinyFriend(friends));

Additional documentation

  • Related