skip to Main Content

My problem in javascript is that I want specific elements in this case location.name to be thrown into change / array so that they don’t repeat [Las "Żółta Górka", Park Wodziczki Poznań, Sala SP 5, Rzeszów].

My json api https://apidemo.outrainer.pl/firms/1/trainings?future=14&past=7

fetch(API_URL)
    .then((res) => res.json())
    .then((trainingsData) => {
        trainings = trainingsData.map((training) => {
            return {
                name: training.name,
                startDate: training.startDate,
                endDate: training.endDate,
                location: training.location.name,
                type: training.location.type
            };
        });
       renderTrainingsList(trainings);

});

const renderTrainingsList = (trainings) => {
    trainings.forEach(training => {
        createTrainingsItemElement(training)
    })
}

I tried to render the entire array from json and throw only location.name into a separate array and at the same time they did not repeat

2

Answers


  1. Use Set to store unique location names and then filter the items.

    const filterItems = () => {
        const uniqueLocation = new Set();
        const trainings = data.filter(training => {
            let locationName = training.location.name;
            if(!uniqueLocation.has(locationName)) {
                uniqueLocation.add(locationName);
                return {
                    name: training.name,
                    startDate: training.startDate,
                    endDate: training.endDate,
                    location: locationName,
                    type: training.location.type
                }
            }
        });
        return trainings;
    }
    Login or Signup to reply.
  2. Throw the name into the array. Then before rendering it, check whether the name is already in the array.

    const renderTrainingsList = (trainings) => {
      const trainingNames = [];
      trainings.forEach(training => {
        if (!trainingNames.includes(training.name)) {
          trainingNames.push(training.name);
          createTrainingsItemElement(training);
        }
      });
      console.log(trainingNames);
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search