Webbie
Webbie

Reputation: 619

How to filter objects in a array based on the properties

How can i filter objects in a array based on the objects properties?

I have this code right now:

products = [

    {
      title: "Bambu shorts 2.0"
    },
    {
      title: "Bambu shorts 2.0"
    },
    {
      title: "Bambu shorts 3.0"
    }
  ]

  uniqueProducts = [];

  $.each products, (i, el) ->
    if $.inArray(el.title, uniqueProducts) == -1
      uniqueProducts.push el
    return

I want to filter the array by the "titel" property of each object. So if the title of the object already exists in the uniqueProducts array it should not add the object.

My code still pushes all three objects to the uniqueProducts array.

Thank you in advaced!

Upvotes: 0

Views: 49

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386730

You could filter with a Set for seen title.

const
    raw_products = [{ title: "Bambu shorts 2.0" }, { title: "Bambu shorts 2.0" }, { title: "Bambu shorts 3.0"  }],
    uniqueProducts = raw_products.filter(
        (s => ({ title }) => !s.has(title) && s.add(title))
        (new Set)
    );

console.log(uniqueProducts);

Upvotes: 1

Related Questions