1

Example:

var someArray = ["My Name is", "My is Name", "Name my is", "is Name my"]

I want to print the last element of each string, so:

output: is, Name, is, my

I have no idea where I should start. My first thought was to split the array and print the last index, but I didn't succeed

1

4 Answers 4

2

Use Array.map

var someArray = ["My Name is", "My is Name", "Name my is", "is Name my"];
let result = someArray.map(v => {
  let temp = v.split(" ");
  return temp[temp.length-1];
})
console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

2

You can use a regular expression to match the last word.

var someArray = ["My Name is", "My is Name", "Name my is", "is Name my"]
var result = someArray.map(item => item.match(/\w+$/)[0]);
console.log(result);

Comments

1
var someArray = ["My Name is", "My is Name", "Name my is", "is Name my"];
var lastElements = "";

someArray.forEach(str => {
  splitStr = str.split(" ");
  lastElements += splitStr[splitStr.length - 1] + ", ";
});

console.log('output: ', lastElements);

//Outputs output:  is, Name, is, my, 

Comments

0

Another simple approach:

const someArray = ["My Name is", "My is Name", "Name my is", "is Name my"]

const output = someArray.map(str => str.split(' ').pop());

console.log(output);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.