Home » Javascript JQuery Examples » Take Top 10 Items from Data Array List Using JavaScript and jQuery

Take Top 10 Items from Data Array List Using JavaScript and jQuery

This post will demonstrate how to take the first 10 items from a data list using JavaScript and jQuery. You can use the slice method to get particular top items from the list.


code snippet:
var filterData = data.slice(0,10);


Retrieving Top 10 Items from JSON Data List


slice method using Javascript:

The below javascript example shows getting the top 10 items from the JSON response data list and assigning the result to another element.

const response = await fetch('URL');
const data = await response.json();

// Get the first 10 items from the JSON data
var filterData = data.slice(0,10);

var top10Result = "";

// Loop through and display the first 10 items
filterData.forEach(obj => {
	top10Result += obj.name + ',';
 });
 
document.getElementById('item-list').innerHTML = top10Result;


slice method using jQuery:

The below jQuery example shows fetching 10 items from the JSON data:

$(document).ready(function() {

  // Your JSON data (replace with your actual data source)
  var jsonData = {
    "items": ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6", "Item 7", "Item 8", "Item 9", "Item 10", "Item 11", "Item 12" ]
  };

  // Get the first 10 items from the JSON data
  var first10Items = jsonData.items.slice(0, 10);

  // Loop through and display the first 10 items
  for (var i = 0; i < first10Items.length; i++) {
    $("#item-list").append("<li>" + first10Items[i] + "</li>");
  }
});
<ul id="item-list">
  <!-- Items will be appended here -->
</ul>

In the code above, we:
  1. Define the JSON data (replace this with your actual JSON source).
  2. Use the slice method to extract the first 10 items from the JSON array.
  3. Loop through the extracted items and append them to an HTML element with the id “item-list.”

Leave a Reply

Your email address will not be published. Required fields are marked *