hungryhippos
hungryhippos

Reputation: 637

How do I split an array with multiple elements to get the last item in JavaScript?

I apologize if this question is too simple, I am just getting started in JavaScript. I have the following problem: A function is returning an array similar to:

[
  "Wed Feb 24 11:39:01 CST 2021",
  "Thu Mar 21 18:35:30 CDT 2019",
  "Tue Feb 26 15:23:50 CST 2019"
]

My challenge is to grab just the year from each of those elements within the array (so I need to grab 2021, 2019, and 2019).

I was thinking in my head to use .split by using space as the delimitator and then using length-1 to get the last element. But my implementation keeps throwing errors.

I tried:

var fromDate = $dateList[*].dates
var fromDateSplit = fromDate.split(' ');
var fromYear = fromDateSplit[fromDateSplit.length - 1]

Please let me know what I am doing wrong. Getting ready to pull hair out.

Thank you in advance for looking at this!

Upvotes: 1

Views: 982

Answers (4)

Mario Varchmin
Mario Varchmin

Reputation: 3782

You could also look for the last space in the strings using string.lastIndexOf(" "), and take what comes afterwards.

const a = [
  "Wed Feb 24 11:39:01 CST 2021",
  "Thu Mar 21 18:35:30 CDT 2019",
  "Tue Feb 26 15:23:50 CST 2019"
]
const years = a.map((e) => e.substring(e.lastIndexOf(" ")));
console.log(years);

Upvotes: 1

Arthur
Arthur

Reputation: 21

Keep your hair on your head and follow me:

On second line, your variable 'fromDateSplit' is trying to split an array, not a string. The split method belongs to string objects. So, you can try iterate over your array and apply the split on the current element of the iteration. Like this:

var array = [
  "Wed Feb 24 11:39:01 CST 2021",
  "Thu Mar 21 18:35:30 CDT 2019",
  "Tue Feb 26 15:23:50 CST 2019"
]

array.forEach(element => {
    var fromDateSplit = element.split(' ');
    var fromYear = fromDateSplit[fromDateSplit.length - 1];
    console.log(fromYear);
});

Upvotes: 1

Spectric
Spectric

Reputation: 31992

Simply split it by spaces and get the last item in the result array:

const a = [
  "Wed Feb 24 11:39:01 CST 2021",
  "Thu Mar 21 18:35:30 CDT 2019",
  "Tue Feb 26 15:23:50 CST 2019"
]
const b = a.map(e => e.split(" ").slice(-1)[0]);
console.log(b);

Upvotes: 1

Lawrence Cherone
Lawrence Cherone

Reputation: 46610

My challenge is to grab just the year from each of those elements within the array (so I need to grab 2021, 2019, and 2019).

With a simple loop and new Date(v).getFullYear().

const arr = [
  "Wed Feb 24 11:39:01 CST 2021",
  "Thu Mar 21 18:35:30 CDT 2019",
  "Tue Feb 26 15:23:50 CST 2019"
]

console.log(arr.map(v => new Date(v).getFullYear()))

Upvotes: 1

Related Questions