-1

I have an array of objects called cars that contains search result listings. In each listing there is an attribute called data-price.

Array Object Example

<li xmlns="http://www.w3.org/1999/xhtml" id="listing-ECAR-R-EY-MCOO001-EY-MCOO001" data-price="94.03"></li>

I'm wondering how I can get the lowest data-price value? And the average data-price value from the array of cars?

Code:

// This prints out each price value

cars.forEach(function(element) {
    console.log(element[0].getAttribute("data-price"));
});
Michael
  • 403
  • 1
  • 9
  • 28

1 Answers1

0

You can use map method in combination with Math.min and reduce functions.

I used reduce method in order to find out the sum of the elements and get the average by divide the sum to the number of elements in cars array.

The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

let prices = cars.map(function(element) {
   return element[0].getAttribute("data-price");
});

let lowestPrice = Math.min(...prices);
let avg = prices.reduce(function(acc, val) { return acc + val; }, 0)/prices.length

Alternative of spread syntax.

let lowestPrice = Math.min.apply(null, prices);
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128