Home > Net >  how can i display an array with the highest price to the lowest
how can i display an array with the highest price to the lowest

Time:02-21

I have connected to an api and have pulled some data into my project with the name of 'data'. This data is being rendered dynamically into a card component. I am now trying to arrange the order from highest price to lowest price on the click of a button with useState but cannot figure it out. Below is what i have so far:

import React, { useState } from "react";
import "./App.scss";
import { useQuery } from "@apollo/react-hooks";
import GET_PRODUCTS_IN_COLLECTION from "./gql/getCollection";
import ProductCard from "./components/ProductCard/ProductCard";

const App = (props) => {
  const { data, loading, error } = useQuery(GET_PRODUCTS_IN_COLLECTION, {
    variables: {
      count: 10,
      handle: "skateboard",
    },
  });

  // console.log(data)

  const [reversed, setReversed] = useState(false);
  const [highLow, setHighLow] = useState(false);
  const [lowHigh, setLowHigh] = useState(false);
  const [remove, setRemove] = useState(false);

  const reverseOrder = () => {
    setReversed(!reversed);
  };

  const highToLow = () => {
    setHighLow(!highLow);
  };

  const lowToHigh = () => {
    setLowHigh(!lowHigh);
  };

  const removeLast = () => {
    setRemove(!remove);
  };

  if (loading) {
    // Data is still loading....
    return <div className="App">Loading....</div>;
  }

  return (
    <div className="App">
      <header className="App-header"></header>
      <main>
        <div className="buttonGroup">
          <button onClick={reverseOrder}>Reverse Product Order</button>
          <button onClick={highToLow}>Price High to Low</button>
          <button onClick={lowToHigh}>Price Low to High</button>
          <button onClick={removeLast}>Display 9 products</button>
        </div>

        {/* 
          Your render components go here
        */}

        <div className="ProductList">
          {reversed
            ? data.collectionByHandle.products.edges
                .slice()
                .reverse()
                .map((product) => {
                  return <ProductCard productData={product} />;
                })
            : highLow
            ? data.collectionByHandle.products.edges
                .slice()
                .sort((a,b) => (a.node.vendor - b.node.vendor))
                .map((product) => {
                  return <ProductCard productData={product} />;
                })
            : lowHigh
            ? data.collectionByHandle.products.edges
                .slice()
                .map((product) => {
                  return <ProductCard productData={product} />;
                })
                .splice(1)
            : remove
            ? data.collectionByHandle.products.edges
                .slice()
                .map((product) => {
                  return <ProductCard productData={product} />;
                })
                .splice(1)
            : data.collectionByHandle.products.edges.map((product) => {
                return <ProductCard productData={product} />;
              })}
        </div>
      </main>
    </div>
  );
};

export default App;

image of array

CodePudding user response:

Assuming the values are alphanumerical javascript has built in function "sort" to do that. Even if they are not numerical there has to be a way to read their value that you can use! Then its pretty straight forward (modified from w3schools):

const fruits = [2,1,"Banana", "Orange", "Apple", "Mango"];
fruits.sort();

will create array [1,2,Apple,Banana,Mango,Orange]

You should be able to do something along these lines in your program.

(just droping: if you want to reverse the order simply use reverse() method on array)

CodePudding user response:

I don't know what your data looks like but this should work.

https://www.w3schools.com/js/js_array_sort.asp

CodePudding user response:

You can change your code like the following example:

Some points to keep in mind :

  1. Try to avoid if statment in JSX .
  2. Put your events in seprated functions to make it easy for you to manage .
import React, { useState } from "react";
import "./App.scss";
import { useQuery } from "@apollo/react-hooks";
import GET_PRODUCTS_IN_COLLECTION from "./gql/getCollection";
import ProductCard from "./components/ProductCard/ProductCard";

const App = (props) => {

  const { data, loading, error } = useQuery(GET_PRODUCTS_IN_COLLECTION, {
    variables: {
      count: 10,
      handle: "skateboard",
    },
  });

  const [myData, setMyData] = useState(data);

    const reverseOrder = () => {
    let newData = myData.reverse();
    setMyData([...newData]);
  };

  const highToLow = () => {
    let newData = myData.sort((a, b) => b.node.vendor- a.node.vendor);
    setMyData([...newData]);
  };

  const lowToHigh = () => {
    let newData = myData.sort((a, b) => a.node.vendor- b.node.vendor);
    setMyData([...newData]);
  };

  const removeLast = () => {
    myData.splice(-1, 1);
    setMyData([...myData]);
  };

  if (loading) {
    // Data is still loading....
    return <div className="App">Loading....</div>;
  }

  return (
    <div className="App">
      <header className="App-header"></header>
      <main>
        <div className="buttonGroup">
          <button onClick={reverseOrder}>Reverse Product Order</button>
          <button onClick={highToLow}>Price High to Low</button>
          <button onClick={lowToHigh}>Price Low to High</button>
          <button onClick={removeLast}>Display 9 products</button>
        </div>

  {
    myData.map((product) => {
            return <ProductCard productData={product} />;
    });
   }
      
        </div>
      </main>
    </div>
  );
};

export default App;
  • Related