Skip to content

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

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

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

            let newcar = [prompt("Enter new car")]
            cars += cars.push(newcar);
            cars.sort(); //here in not working
            document.getElementById("add").innerHTML = cars;

enter image description here

enter image description here



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 +=)