SkyeBoniwell
SkyeBoniwell

Reputation: 7122

filter is not returning the filtered array

I have an array like this:

  let swCharacters = [
    { id: 0, name: "Luke", seriesId: 1 },
    { id: 1, name: "Han", seriesId: 1 },
    { id: 2, name: "Din Djarin", seriesId: 4 },
    { id: 3, name: "Anakin", seriesId: 2 },
    { id: 4, name: "Yoda", seriesId: 1 },
    { id: 5, name: "Grogu", seriesId: 4 }
  ];

And I want to filter out everything except those that have a seriesId of 4, so I found this to help:

 swCharacters = swCharacters.filter(x => x.seriesId === 4).map(x => x.seriesId)
        console.log("The Mandalorian: ", swCharacters);
    

But this isn't doing what I need it to do.

It is just creating an array with 4 as the only member, like [4, 4].

I need the filtered array to look like:

[{ id: 3, name: "Din Djarin", seriesId: 4 }, { id: 6, name: "Grogu", seriesId: 4 }]

Can I do this with javascript?

Thanks!

Upvotes: 1

Views: 47

Answers (2)

Aalexander
Aalexander

Reputation: 5004

You can just call filter directly on swCharacters.

const res = swCharacters.filter(x => x.seriesId === 4);

let swCharacters = [{
    id: 0,
    name: "Luke",
    seriesId: 1
  },
  {
    id: 1,
    name: "Han",
    seriesId: 1
  },
  {
    id: 2,
    name: "Din Djarin",
    seriesId: 4
  },
  {
    id: 3,
    name: "Anakin",
    seriesId: 2
  },
  {
    id: 4,
    name: "Yoda",
    seriesId: 1
  },
  {
    id: 5,
    name: "Grogu",
    seriesId: 4
  }
];


const res = swCharacters.filter(x => x.seriesId === 4);
console.log(res)

When you chain it with map then first it will apply

map(x => x.seriesId)

This returns an array of all seriesId's as input for your filter. The filter than check in the array for all seriesIds with value 4 and returns it as array.

This will result in

[4, 4]

let swCharacters = [{
    id: 0,
    name: "Luke",
    seriesId: 1
  },
  {
    id: 1,
    name: "Han",
    seriesId: 1
  },
  {
    id: 2,
    name: "Din Djarin",
    seriesId: 4
  },
  {
    id: 3,
    name: "Anakin",
    seriesId: 2
  },
  {
    id: 4,
    name: "Yoda",
    seriesId: 1
  },
  {
    id: 5,
    name: "Grogu",
    seriesId: 4
  }
];

  swCharacters = swCharacters.filter(x => x.seriesId === 4).map(x => x.seriesId)
console.log(swCharacters);

Upvotes: 2

Mvrocha
Mvrocha

Reputation: 403

You should not use map function, just filter, like this:

 swCharacters = swCharacters.filter(x => x.seriesId === 4)
 
 console.log("The Mandalorian: ", swCharacters);

Upvotes: 2

Related Questions