Array metoder



Testa kodexemplet:


    Kodexempel

    <div class="input-group mb-3">
        
        <ul id="ulCarArrays"></ul>
    </div>
    <script>
    // This example demonstrates various array methods in JavaScript
    // It includes filtering, mapping, finding, and sorting an array of car objects
    
    //cars is an array of car objects, each with properties like id, brand, model, year, price, and isElectric
    const cars = [
      { id: 1, brand: "Toyota", model: "Camry", year: 2020, price: 24000, isElectric: false },
      { id: 2, brand: "Tesla", model: "Model 3", year: 2022, price: 45000, isElectric: true },
      { id: 3, brand: "Ford", model: "Mustang", year: 2021, price: 38000, isElectric: false },
      { id: 4, brand: "BMW", model: "X5", year: 2023, price: 52000, isElectric: true },
      { id: 5, brand: "Honda", model: "Civic", year: 2019, price: 22000, isElectric: false },
    ];
    
    const ul = document.querySelector("#ulCarArrays");
    
    //"filter"  is used to create a new array with all elements that pass the test implemented by the provided
    // arrow function In this case, it filters out electric cars
    const electricCars = cars.filter(car => car.isElectric);
    //innerHTML is used to set the content of the unordered list
    //stringify is used to convert the array to a JSON string for display
    // The second parameter null, meanas no replacer function is need and the third parameter 2 are 
    //used to format the JSON string with indentation
    // Output: as json the two Tesla & BMW (isElectric: true)
    ul.innerHTML="<li>"+JSON.stringify(electricCars, null, 2)+"</li>"; 
    
    //"map" is used to create a new array with the results of calling a provided arrow function on 
    // every element in the calling array
    // In this case, it extracts the model names of the cars
    const carModels = cars.map(car => car.model);
    // Output: [ "Camry", "Model 3", "Mustang", "X5", "Civic" ]
    ul.innerHTML+="<li>"+JSON.stringify(carModels, null, 2)+"</li>"; 
    
    //"find" is used to find the first element in the array that satisfies the provided testing arrow function
    // In this case, it finds the car with id 3
    const carWithId3 = cars.find(car => car.id === 3);
    // Output: { id: 3, brand: "Ford", model: "Mustang", year: 2021, price: 38000, isElectric: false }
    ul.innerHTML+="<li>"+JSON.stringify(carWithId3, null, 2)+"</li>";   
    
    //"sort" is used to sort the elements of an array in place and return the sorted array
    // In this case, it sorts the cars by price in ascending order  
    const sortedCars = cars.sort((carA, carB) => carA.price - carB.price);
    //// Output: sorted array of cars by price
    ul.innerHTML+="<li>"+JSON.stringify(sortedCars, null, 2)+"</li>"; 
    
    </script>