skip to Main Content

I have this file CarsData.js (content some info)

const CarsData = [
  { id: "car_01",  image: imageToyota,     title: "Toyota",      type: "SUV" },
  { id: "car_02",  image: imageAudi,       title: "Audi",        type: "SUV" },
  { id: "car_03",  image: imageNissan,     title: "Nissan",      type: "CAR" },
  { id: "car_04",  image: imageKia,        title: "Kia",         type: "TRUCK" }
]

export default CarsData

and I display all the code in this section CardsCars.js

const CardsCars = () => {

  const card = CarsData.map(car => {
    return <CardCar image={car.image} title={car.title} type={car.type}/>
  })

  return (
  <>
    <div className='row'>

        {card} //display all the info in CarsData

    </div>
  </>
  )
}

export default CardsCars

How can I display only 2 info from CarsData.js (not 4 info)

2

Answers


  1. You can use the "slice()" method which returns selected elements in an array, as a new array. Then You can run "map()" to show the data.

    CarsData.slice(0,2).map((car) => (<CardCar image={car.image} title={car.title} type={car.type}/>));
    

    In this case, the first 2 info will be displayed.

    Login or Signup to reply.
  2. If you want n random numbers, you may consider the following approach:

    const randomNElements = (arr = [], n = 2) => {
      const copy = [...arr];
      const result = [];
      const length = Math.min(n, copy.length);
      for (let i = 0; i < length; i++) {
        const [randomElement] = copy.splice(Math.floor(Math.random() * copy.length), 1);
    
        result.push(randomElement);
      }
    
      return result;
    };
    

    It doesn’t mutate the initial array and doesn’t preserve the order of selected elements from initial array

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search