How to return all names with second letter "h" - from an array of names?

Viewed 170

I have to write a function that returns all users with a second letter of "h" in their name.

var users = ["Roman","Sherry","Sandrah","Shamaika"];

I started to code something like this but it is not working.

function letter(){
    var index = users.indexOf("h") == [1];
    return(index);
}

I am new to JavaScript and I am not sure where to start.

7 Answers

You can use filter.

const users = ["Roman","Sherry","Sandrah","Shamaika"];

let filteredUsers = users.filter(user => user.charAt(1) === 'h');
console.log(filteredUsers);

You could filter the array by taking a function which check the character at index 1.

function checkLetter1(string) {
    return string[1] === 'h';
}

var users = ["Roman", "Sherry", "Sandrah", "Shamaika"];

console.log(users.filter(checkLetter1));

You are missing filter

var users = ["Roman","Sherry","Sandrah","Shamaika"];

var index = users.filter(a=> a.indexOf("h") === 1);
console.log(index);

Currently, your code is looking for the first index of h in the array of user names, which will return incorrect results. Consider using the Array#filter method to select names that match your criteria of the second character being h like so:

var users = ["Roman","Sherry","Sandrah","Shamaika"];

function letter(name){
    // Return true if the second character of name is an 'h'
    return name[1] === 'h';
}

// Use filter() method to get array of items that satisfy
// the criteria of your letter() function
var filteredUsers = users.filter(letter);

console.log(filteredUsers);

You can do something like so:

function usersWithSecondH(users) {
  return users.filter(user => user[1] === 'h');
}

So essentially checking the value of the second letter and returning those names in a new array if it matches 'h';

var users = ["Roman","Sherry","Sandrah","Shamaika"];
var t=users.filter((x)=>x.indexOf('h')==1)
console.log(t);

This will do

The following function will return the array elements (as a result array) which have the second character as a "h":

var users = ["Roman", "Sherry", "Sandrah", "Shamaika"];

function getMyUsers() {
    return users.map(user => user.split(""))
                .filter(userChars => userChars[1] == "h")
                .map(userChars => user.join(""));
};

console.log(getMyUsers());

The Output:

[ "Sherry", "Shamaika" ]


EDIT: The getMyUsers function can also be coded in a more detailed way as follows:

function getMyUsers2() {

    let usersWithH = [];

    for (let user of users) {
        let userChars = user.split("");
        if (userChars[1] == "h") {
            usersWithH.push(user);
        }
    }

    return usersWithH;
}

console.log(getMyUsers2()); // prints [ "Sherry", "Shamaika" ]
Related