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
JavaScript
x
18
18
1
<body>
2
<button id="addbtn">Add cars to list</button>
3
<p id="add"></p>
4
5
<script>
6
let cars = ["bmw", "honda", "toyota", "ford"];
7
8
$(document).ready(function(){
9
$("#addbtn").click(function(){
10
$("#add").show(1000);
11
let newcar = [prompt("Enter new car")]
12
cars += cars.push(newcar);
13
cars.sort(); //here in not working
14
alert(cars);
15
document.getElementById("add").innerHTML = cars;
16
})
17
})
18
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:
JavaScript
1
5
1
let cars = ["bmw", "honda", "toyota", "ford"];
2
const newcar = [prompt("Enter new car")]
3
cars.push(newcar); //Change this line (remove car +=)
4
cars.sort();
5