user1978298
user1978298

Reputation: 15

How to compare Chars of separate String values stored in an array? Javascript

I have an array that contains three different strings for example:

[ 'obtain wealth1', 'obtain dreams3', 'obtain discretion3' ]

The array is created from a function I've written.

What I want to do next is compare the last characters of the strings to one another (the numbers) to see if I produce a match.

How would I go about doing this?

Thanks for the help.

Upvotes: 0

Views: 3820

Answers (2)

David G
David G

Reputation: 96810

First loop through the array and determine (with an if statement) if the elements held at the positions in the array have, as its last character, a value equal to the number you wish. You can add else if statements to check for multiple conditions. We use the slice method with an argument of -1 to check for the rightmost character in the string.

for (var i = list.length; i--;) {
    if (list[i].slice(-1) == the_number) {

    } else {}
}

Upvotes: 3

Zim84
Zim84

Reputation: 3497

With string functions for example: http://www.w3schools.com/jsref/jsref_obj_string.asp

var a = [ 'obtain wealth1', 'obtain dreams3', 'obtain discretion3' ];
var length = a.length;
var lastchar = a.charAt(length - 1);

Upvotes: 0

Related Questions