Home > Net >  How to sort array object after foreach lopping?
How to sort array object after foreach lopping?

Time:07-26

I have some array object below. I want to sort data by id after foreach looping, i was using sort() but there's error. How can i sort my data and loop sequentially?

$(document).ready(function(){
  const data = [
    {
      id : 3,
      name: 'John'
    },
    {
      id : 1,
      name: 'Doe'
    },
    {
      id : 2,
      name: 'Lorem'
    },
  ]

  data.forEach((item, index) => {  
    item.sort(function(a, b) {
      $('.data').append(`<ul>
        <li>${item.id}</li>
      </ul>`);
    });
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div ></div>

CodePudding user response:

Try sorting first then forEach() afterward:

$(document).ready(function() {
  const data = [{
      id: 3, name: 'John'
    },
    {
      id: 1, name: 'Doe'
    },
    {
      id: 2, name: 'Lorem'
    },
  ];

  data.sort((a, b) => a.id - b.id).forEach((item) => {
    $('.data').append(`<ul>
      <li>${item.id}</li>
    </ul>`);
  });  
})

CodePudding user response:

View exception messages

item.sort is not a function TypeError: item.sort is not a function

Either convert the values you call the sort() method to an array, or make sure you only call the sort method on valid arrays

According to the data format of your question, it is recommended that you sort first and then forEach.

$(document).ready(function() {
  const data = [
    {id: 3, name: 'John'},
    {id: 1, name: 'Doe'},
    {id: 2, name: 'Lorem'},
  ];

  // Sorts the data array by id in ascending order
  data.sort((a, b) => a.id - b.id);
  
  // Pass in each element of the sorted array and execute the given function once
  data.forEach(({id}) => {
    $('.data').append(`<ul><li>${id}</li></ul>`);
  });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div ></div>

But if in fact, the data format is more complex, such as an array of multiple array elements, and each array element represents a set of li, you can refer to the following code snippet.

$(document).ready(function() {
  const data = [
    [
      {id: 3, name: 'John'},
      {id: 1, name: 'Doe'},
      {id: 2, name: 'Lorem'}
    ],
    [
      {id: 2, name: 'Lorem'},
      {id: 1, name: 'Doe'},
      {id: 3, name: 'John'}
    ]
  ];

  // Sorts the data array by id in ascending order
  data.sort((a, b) => a.id - b.id);

  // Pass in each array element of the array and execute the given function once
  data.forEach(item => {
    const $ul = 
      $('<ul/>').append(
        item
          .sort((a, b) => a.id - b.id)
          .map(({id}) => $(`<li>${id}</li>`))
      );
    $('.data').append($ul);
  });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div ></div>

  • Related