Retrieve every first object

Hello,

How can I retrieve every first object that differs by first property value?

My object:

const carsArr = [
  { make: "bmw", model: "e46", price: "1000" }, // get this one
  { make: "bmw", model: "e52", price: "2000" },
  { make: "bmw", model: "X5", price: "4000" },
  { make: "bmw", model: "TT", price: "1000" },
  { make: "audi", model: "A3", price: "1500"}, // and this one
  { make: "audi", model: "A4", price: "2500"},
  { make: "audi", model: "TT", price: "2800"},
  { make: "audi", model: "A8", price: "3500"}
];

I want to get:

const newCarsArray = [
  { make: "bmw", model: "e46", price: "1000" },
  { make: "audi", model: "A3", price: "1500"}
];
// untested
var newCarsArray = carsArr.reduce(function (arr, item) {
  if (arr.filter(val => val.make === item.make).length === 0) {
    arr.push(item)
  }
  return arr
}, [])
2 Likes

Tested and linted:

var newCarsArray = carsArr.reduce(function (arr, item) {
    if (arr.filter((val) => val.make === item.make).length === 0) {
        arr.push(item);
    }
    return arr;
}, []);

With a test page at https://jsfiddle.net/cj0dx7z8/

2 Likes

Thank you guys! :slight_smile:

where you don’t know the name of your properties or object
without using a loop like for … in or jQuery’s $.each
For example, I need to access sh1 object without knowing the name of sh1:

var example = 
{
    sh1: { /* stuff1 */},
    sh2: { /* stuff2 */},
    sh3: { /* stuff3 */}
};

Use Object.keys() to retrieve object properties to array.

var example = 
{
    sh1: { /* stuff1 */},
    sh2: { /* stuff2 */},
    sh3: { /* stuff3 */}
};

var keys = Object.keys(example);

keys.forEach( function(e) {
    console.log(e)
});

// output
sh1
sh2
sh3
2 Likes

@shwetakakran01 Is this related to this particular thread, or was it intended to be a new question? Currently, it’s none too clear.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.