Making a Unique Array of Values from an Existing Array - J Query

Problem
You have an ordered list on your page. You select all the <li>elements of that list using jQuery; now you need to transform that list into another list.

Solution

Let’s say we have a list of people in an ordered list. We would like to display the first three people from that ordered list as a sentence:

Making-a-Unique-Array-of-Values-from-an-Existing-Array

Figure : shows the output.

We start by making an array of the <li>elements from the ordered list. We will select all <li>elements on the page by using a jQuery selector and pass that in as an argument of the jQuery utility method $.map(), which will take an existing array and “map” it in to another array. The second argument is the function that will iterate through the array, perform translations, and return a new value to be stored into a new array. In the preceding example, we iterate through the array we made, return only thehtml() values of the first three list elements, and map these values into a new array. We then take that array and use the join method to make a single string out of the array and inject it into the end of the document.

Discussion

In the solution, we are using the jQuery utility method $.map(), which will transform an existing array into another array of items. $.map() takes two arguments, an array and a callback function:

$.map() will iterate through each item of the original array and pass in the item to be translated and the index of the current location within the array. The method is expecting a value to be returned. The returned value will be inserted into the new array.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

J Query Topics