Jeremiah Saunders
Jeremiah Saunders

Reputation: 1

Returning the first two odd numbers in an array

I have to run a code that picks out the odd numbers in an array, and returns the first two odd numbers in that array. I've figured out how to return all of the odd numbers from the array, just not the first two.

code so far:

function oddCouple(_numberList) {
  let numberList = [5, 2, 3, 1];
  let oddNumbers = numberList.filter((number) => number % 2 !== 0);

  console.log(oddNumbers);
}
oddCouple();

Any help would be appreciated!

Upvotes: 0

Views: 1413

Answers (4)

zb22
zb22

Reputation: 3231

You can use for..of loop, and break when the array contains 2 items like so:

function oddCouple(_numberList) {
  let numberList = [5, 2, 3, 1];
  let arr = [];
  for(let number of numberList) {
    (number % 2) !== 0 && arr.push(number);
    if(arr.length === 2) break;
  }

  console.log(arr);
}
oddCouple();

Upvotes: 2

Alexander Higgins
Alexander Higgins

Reputation: 6923

The built in method would be Array.slice. This code would be suitable for a small arrays.

For larger arrays it would be more efficient to manually loop through the source array so you are only evaluating the modulus operation for the first N odd numbers.

Additionally, division is expensive. You can check if a number is odd using the binary & operator; e.g.: (number & 1) == 1

function oddCouple(_numberList) {
  let numberList = [5, 2, 3, 1];
  let oddNumbers = numberList.filter((number) => (number & 1) == 1).slice(0,2);

  console.log(oddNumbers);
}
oddCouple();

Upvotes: 2

Maxwell Jhonson
Maxwell Jhonson

Reputation: 153

function oddCouple(_numberList) {
  let numberList = [5, 2, 3, 1];
  let oddNumbers = numberList.filter((number) => number % 2 !== 0).slice(0,2);

  console.log(oddNumbers);
}

Upvotes: 0

Kinglish
Kinglish

Reputation: 23654

Array.slice returns the selected number of items from the array starting from a specified index.

function oddCouple(_numberList) {
  let oddNumbers = _numberList.filter((number) => number % 2 !== 0).slice(0, 2);

  console.log(oddNumbers);
}
oddCouple([1, 2, 3, 4, 5, 6, 7, 8, 9]);

Upvotes: 2

Related Questions