Estoy tratando de ordenar datos en una matriz de objetos. El problema es que no tengo ninguna propiedad de fecha, por lo que no puedo mostrar los datos más recientes,
Estoy tratando de ordenarlo de esta manera, pero no funciona.
const filter2 = data.sort((a, b) => (a > b ? -1 : 1))Aquí está mi ejemplo de datos
const data = [ { _id: "6221943a03931299eb8c343b", title: "product 1", brand: "Beats", reg_price: "299", sale_price: "200", stock: "150", }, { _id: "6221943a03931299eb8c343b", title: "product 2", brand: "Beats", reg_price: "299", sale_price: "200", stock: "150", }, { _id: "6221943a03931299eb8c343b", title: "product 3", brand: "Beats", reg_price: "299", sale_price: "200", stock: "150", }, { _id: "6221943a03931299eb8c343b", title: "product 4", brand: "Beats", reg_price: "299", sale_price: "200", stock: "150", }, { _id: "6221943a03931299eb8c343b", title: "product 4", brand: "Beats", reg_price: "299", sale_price: "200", stock: "150", }, ]Puede hacerlo así si desea ordenarlo con respecto a la propiedad del objeto
const data = [ { _id: "6221943a03931299eb8c343b", title: "product 1", brand: "Beats", reg_price: "299", sale_price: "200", stock: "150", }, { _id: "6221943a03931299eb8c343b", title: "product 2", brand: "Beats", reg_price: "299", sale_price: "200", stock: "150", }, { _id: "6221943a03931299eb8c343b", title: "product 3", brand: "Beats", reg_price: "299", sale_price: "200", stock: "150", }, { _id: "6221943a03931299eb8c343b", title: "product 4", brand: "Beats", reg_price: "299", sale_price: "200", stock: "150", }, { _id: "6221943a03931299eb8c343b", title: "product 4", brand: "Beats", reg_price: "299", sale_price: "200", stock: "150", }, ] // sortProperty = '_id' | 'title' | 'brand' | 'reg_price' | 'sale_price' | 'stock' const sortFunc = (sortArr,sortProperty) => sortArr.sort((a,b) => a[sortProperty] - b[sortProperty]) console.log(sortFunc(data,'_id'))