skip to Main Content

I have this code.

console.log(
  "deleteHandler:",
  ...images.filter((image) => image._id !== imageId)
);

Docs say that filter returns an array. I expect the console output to return an array but it returns an object.

deleteHandler: {user: {…}, _id: ‘asdf’, likes: Array(0), public: true, key: ‘asdf.jpeg’, …}

If I wrap it in an array I get an array in the console:

console.log(
  "deleteHandler:",
  [...images.filter((image) => image._id !== imageId)]
);

deleteHandler: (2) [{…}, {…}]

But I do not understand why.

3

Answers


  1. It would be really helpful if you would share how ...images and images looks like.

    Maybe images is an object and you are trying to look for something inside of that obj that is an array? For example: images.someImages

    Login or Signup to reply.
  2. Without […]: You’re spreading individual elements as separate arguments, and it’s displayed as objects.
    With […]: You’re creating a new array and spreading elements into it, so it’s correctly displayed as an array.
    So, the behavior is due to how the spread operator interacts with console.log when spreading individual elements vs. spreading elements into a new array.

    Login or Signup to reply.
  3. This will work, yours didn’t because the ... spreads the array.

    console.log(
      "deleteHandler:",
      images.filter((image) => image._id !== imageId)
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search