0

It's possible that I'm doing something wrong, but I do not understand the following result. I get the product Array (sorted by name) from the server. Now I need the lowest and highest price for a price slider so that I'm using computed properties. After that, the complete product array is sorted by price and I can't understand why?

    data:
      products: []
      ...
      methods: {
        loadProducts() {
          ...
          this.products = response.data.elements; //array is sorted correct by name
        }
      },
      computed: 
        maxPriceCalc: function() {
          var products = this.products;
          if(productss.length > 0) {
            var maxPrice = productss.sort(compare); //at this point - this.products is sorted by price too
            return maxPrice[0].calculatedPrice.totalPrice;
          }
          function compare(a, b) {
            if (a.calculatedPrice.totalPrice > b.calculatedPrice.totalPrice)
                return -1;
            if (a.calculatedPrice.totalPrice < b.calculatedPrice.totalPrice)
                return 1;
            return 0;
          }
          ...

Maybe anyone has an idea to figure it out.

Thx for time and help.

1 Answer 1

3

Two reasons in play here (nothing to do with Vue - just plain old JavaScript):

  1. Array is the type handled by reference so your local products variable is pointing to the same array as this.products
  2. Array.prototype.sort() sorts the array in-place (not creating new array)

The easy solution is to use the spread operator to create a new array. Instead of var products = this.products, use var products = [...this.products]. This will create a completely new array with the same elements as the original array...

Although as you need min and max value at the same time, it would be really much better to implement this computed prop without any sorting just by scanning the source array with forEach, computing both values at the same time, and returning a simple object like this { minPrice: xx, maxPrice: yy }

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.