1

I have a problem with my carPassing function. I'm trying to add a object literate into an array. Console log is a number instead of an array list. Why is that so? What am I doing wrong?

If the array is too big, does it just give the sum instead?

obtained:

4

expected:

[
  {
    time: 1568329654807,
    speed: 40,
  },
  {
    time: 1568329821632,
    speed: 42,
  },
  {
    time: 1568331115463,
    speed: 35
  },

  {
    time: 1568331115463,
    speed: 38
  }
]

Tried: Quick Google, splicing, alternative inputs, printing separately and unshift.

Code:

const carPassing = function(cars, speed){
  return cars.push({time: Date.now(), speed: speed});
}

const cars = [
  {
    time: 1568329654807,
    speed: 40,
  },
  {
    time: 1568329821632,
    speed: 42,
  },
  {
    time: 1568331115463,
    speed: 35
  }
]

const speed = 38

console.log(carPassing(cars, speed));
stateMachine
  • 5,227
  • 4
  • 13
  • 29
Weltgeist
  • 137
  • 1
  • 1
  • 11

1 Answers1

3

As mentioned in the array .push() docs:

The push() method adds zero or more elements to the end of an array and returns the new length of the array.

and as in your code you are simply returning

return cars.push({time: Date.now(), speed: speed});

It is actually doing the same. If you wan to get the updated array list, you can simply return the array instead of push result like:

const carPassing = function(cars, speed){
  cars.push({time: Date.now(), speed: speed});
  return cars;
}

Working Demo:

const carPassing = function(cars, speed){
  cars.push({time: Date.now(), speed: speed});
  return cars
}

const cars = [
  {
    time: 1568329654807,
    speed: 40,
  },
  {
    time: 1568329821632,
    speed: 42,
  },
  {
    time: 1568331115463,
    speed: 35
  }
]

const speed = 38
console.log(carPassing(cars, speed));
.as-console-wrapper { max-height: 100% !important; top: 0; }
palaѕн
  • 72,112
  • 17
  • 116
  • 136