Tengo problemas para ordenar los elementos de la matriz según el número de variable. Una vez ordenados, deben insertarse en la tabla. Intento usar la ordenación en el elemento, pero aparece el error.
Obtuve el siguiente error:
item.sort no es una función
¿Cómo puedo resolver?
let myArr = [{ type : "Image", id_a: '123456', number: 2, id: 2, },{ type: 'Text', id_a: '123456', number: 4, id: 4 },{ type: 'Testo', id_a: '564312', number: 1, id: 1},{ type: 'Title', id_a: '123456', number: 3, id: 3 } ] var id_url=123456; var results = {}; for (var i = 0, len = myArr.length; i < len; i++) { var id_art = myArr[i].id_a; if (id_art == id_url) { results[i] = myArr[i]; } } console.log(results); Object.entries(results).forEach(item => { item = item[1]; console.log(item) item.sort(function (a, b) { if (a.number != b.number) { return (a.number - b.number); } }); let child = document.createElement("tr"); child.innerHTML = ` <td>${item.number}</td> <td>${item.type}</td>`; document.querySelector('#my-table').appendChild(child); }) <table id="my-table" width="90%"> <tr> <th>Number</th> <th>Type</th> </tr> </table>Su función de clasificación es correcta, pero ordenar es una función integrada para matrices que toman una función como parámetro. Puedes usarlo como a continuación:
let myArr = [{ type : "Image", id_a: '123456', value: 'moto_guzzi_v100_mandello.jpg', number: 2, id: 2, },{ type: 'Text', id_a: '123456', value: 'The star of the Piaggio group stand is without doubt ... Discover all his secrets with our video', number: 4, id: 4 },{ type: 'Testo', id_a: '564312', value: 'Let find out together with our video', number: 1, id: 1},{ type: 'Title', id_a: '123456', value: 'Moto Guzzi V100 Mandello, the queen of EICMA 2021', number: 3, id: 3 } ] var id_url=123456; var results = {}; for (var i = 0, len = myArr.length; i < len; i++) { var id_art = myArr[i].id_a; if (id_art == id_url) { results[i] = myArr[i]; } } console.log(results); console.log("Before Sort", myArr); const sortedArr = myArr.sort(function (a, b) { if (a.number != b.number) { return (a.number - b.number); } }); console.log("After Sort", sortedArr);Pruebe lo siguiente.
Es más fácil de ordenar.
const filterList = myArr.filter((now) => now.id_a == id_url); const sortList = filterList.sort((a, b) => a.number - b.number); const results = { ...sortList }; for (const item of sortList) { let child = document.createElement("tr"); child.innerHTML = ` <td>${item.number}</td> <td>${item.type}</td>`; document.querySelector("#my-table").appendChild(child); }