beepbopdev
beepbopdev

Reputation: 11

array[i].(split) is not a function

Trying to sort through an array for artists that lived through the twentieth century. The numbers in the year property of the array are strings rather than numbers:
"years" : "1471 - 1528" So I'm trying to split all the years, convert them to numbers, then compare the numbers that way. But when I log to console, I get an error that says "array[i].split is not a function". I've tried array.years.split(" ") and gotten an error as well. I'm just learning JS so bear with me if it's an obvious mistake, but can anyone tell me what I'm doing wrong? Here's a part of the array:

const artists = [
  { "name": "artist name", "years": "1884 - 1920"} ,
...
]

function getYears (array) {
 const newArray = [];
  for (let i = 0; i < array.length; i++) {
   const splitYears = array[i].split(" ");
   splitYears.splice("-")
   Math.floor(splitYears);
    if (splitYears[0] > 1900 && splitYears[1] < 2000) {
      return newArray.push(array[i].name);
    }
  }
  return newArray;
}
console.log(getYears(artists));

Upvotes: 0

Views: 115

Answers (1)

kshetline
kshetline

Reputation: 13744

I'm only guessing because you aren't showing the full content of the array, but I suspect you want something closer to:

array[i].year.split(" ")

Further, rather that split on the spaces, it would make more sense to split on the spaces and the dash together, using a regex that doesn't care about how many spaces (if any) are present:

array[i].year.split(/\s*-\s*/)

The above will return a single-element array when there is one year, a two-element array when a range of years is given.

One further step would be to convert the array to numbers instead of strings:

array[i].year.split(/\s*-\s*/).map(n => parseInt(n, 10))

Upvotes: 3

Related Questions