Skip to content
Advertisement

jQuery sort() is not working in function()

I am trying to sort the array after adding new entry into the array using push(). However there are 2 errors. First the sort() is not allowed. Second is when I remove the sort() the new entry always showed with a number of 5 attached

<body>
<button id="addbtn">Add cars to list</button>
<p id="add"></p>

<script>
let cars = ["bmw", "honda", "toyota", "ford"];

  $(document).ready(function(){
  $("#addbtn").click(function(){
            $("#add").show(1000);
            let newcar = [prompt("Enter new car")]
            cars += cars.push(newcar);
            cars.sort(); //here in not working
            alert(cars);
            document.getElementById("add").innerHTML = cars;
          })
    })

enter image description here

enter image description here

Advertisement

Answer

When adding new object into an array, you only need to use arr.push(obj), and it will return the length of array (5 in your case) and by using += you are changing array to string and adding the 5 at the end of it therefor the sort will not work.

So you must change your code to:

let cars = ["bmw", "honda", "toyota", "ford"];
const newcar = [prompt("Enter new car")]
cars.push(newcar); //Change this line (remove car +=)
cars.sort();
Advertisement