Определить значение выброса в массиве строк - VanillaJS & parseInt - PullRequest
0 голосов
/ 11 февраля 2019

Имеется строка из четных и нечетных чисел, найдите, которая является единственным четным числом или единственным нечетным числом.

Примеры: deteOutlierValue ("2 4 7 8 10");// => 2 - третье число нечетное, в то время как остальные числа четные

Почему мне нужно снова анализировать (четные), даже если я уже все преобразовал в числа?

function detectOutlierValue(str) {
  //array of strings into array of numbers
  newArr = str.split(" ").map(x => parseInt(x))

  evens = newArr.filter(num => num % 2 === 0)
  odds = newArr.filter(num => num % 2 !== 0)

  //if the array of evens has just 1 item while the majority is odds, we want to return the position of that item from the original string.

  if (evens.length === 1) {
    return newArr.indexOf(parseInt(evens)) 
  } else {
    return newArr.indexOf(parseInt(odds)) 
  }
}

Ответы [ 2 ]

0 голосов
/ 11 февраля 2019

Причина в том, что evens и odds не numbers. Они arrays.В этом случае odds = [7]. То есть parseInt([7]), чтобы получить 7. См. Шансы в консоли.Вы возвращаете odds[0] и evens[0]

function detectOutlierValue(str) {
  //array of strings into array of numbers
  newArr = str.split(" ").map(x => parseInt(x))

  evens = newArr.filter(num => num % 2 === 0)
  odds = newArr.filter(num => num % 2 !== 0)
  //if the array of evens has just 1 item while the majority is odds, we want to return the position of that item from the original string.

  if (evens.length === 1) {
    return newArr.indexOf(evens[0]) 
  } else {
    console.log("odds =",odds);
    return newArr.indexOf(odds[0]) 
  }
}
console.log(detectOutlierValue("2 4 7 8 10"))
0 голосов
/ 11 февраля 2019

Это потому, что evens и odds являются массивами в то время, когда вы помещаете их в indexOf.Попробуйте заменить последние две строки первым значением каждого массива:

function detectOutlierValue(str) {
  //array of strings into array of numbers
  newArr = str.split(" ").map(x => parseInt(x))

  evens = newArr.filter(num => num % 2 === 0)
  odds = newArr.filter(num => num % 2 !== 0)

  //if the array of evens has just 1 item while the majority is odds, we want to return the position of that item from the original string.

  if (evens.length === 1) {
    return newArr.indexOf(evens[0]) 
  } else {
    return newArr.indexOf(odds[0]) 
  }
}
...