Mapping and Converting to Arrays
In this page:
map()
.map() runs a function over each element in a selection and collects the returned values into a brand-new jQuery object. Unlike each(), which is for side effects, map() is meant to transform each element into some other value.
Example: map()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<li>One</li><li>Two</li>
<script>
const texts = $("li").map(function() {
return $(this).text();
}).get();
console.log(texts);
</script>
</body>
</html>
get()
get() converts a jQuery collection into a plain JavaScript array of the underlying DOM elements, stripping away jQuery's wrapper. Passing an index to get() instead returns just the single raw DOM element at that position.
Example: get()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<li>One</li><li>Two</li>
<script>
const rawArray = $("li").get();
console.log(rawArray[0].tagName);
</script>
</body>
</html>
toArray()
toArray() converts all matched DOM elements into a plain array, functionally equivalent to calling get() with no arguments. Either one is the bridge point when you need to hand your selection off to regular JavaScript array methods.
Example: toArray()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<li>One</li><li>Two</li>
<script>
const rawArray = $("li").toArray();
console.log(rawArray.length);
</script>
</body>
</html>
map() and Array Methods
After converting a selection to a plain array with get() or toArray(), normal JavaScript array methods like map, filter, and reduce become available, which jQuery's own map() doesn't fully replicate. This is useful when you need array behavior jQuery doesn't provide directly.
Example: map() and Array Methods
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<input value="10"><input value="20">
<script>
const values = $("input").toArray().map(function(el) { return Number(el.value); });
console.log(values.filter(v => v > 10));
</script>
</body>
</html>
Mapping Practice
Mapping is useful when you need data extracted from a set of elements -- like collecting every input's value into a plain array -- rather than the DOM elements themselves. It turns a page's markup into ordinary JavaScript values you can process further.
Example: Mapping Practice
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<input value="a"><input value="b">
<script>
const values = $("input").map(function() {
return $(this).val();
}).get();
console.log(values);
</script>
</body>
</html>
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: