• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / Miscellaneous / Transform the items in an array and create a new one

Transform the items in an array and create a new one

Transform the items in an array and create a new one

Iterate through each item in an array, transform it, and return a new array. The callback accepts three arguments: the current item in the loop’s value, its index, and the array itself.

/**
 * Double each number in an array
 */

var numbers = [1, 4, 9];
var doubles = numbers.map(function(num) {
	return num * 2;
});

// logs [2, 8, 18]
console.log(doubles);


/**
 * Get an array of just names
 */
var data = [
	{
		name: 'Kyle',
		occupation: 'Fashion Designer'
	},
	{
		name: 'Liza',
		occupation: 'Web Developer'
	},
	{
		name: 'Emily',
		occupation: 'Web Designer'
	},
	{
		name: 'Melissa',
		occupation: 'Fashion Designer'
	},
	{
		name: 'Tom',
		occupation: 'Web Developer'
	}
];

var names = data.map(function (item) {
	return item.name;
});

// logs ["Kyle", "Liza", "Emily", "Melissa", "Tom"]
console.log(names);

Source

https://vanillajstoolkit.com/reference/arrays/array-map/

Miscellaneous

Related Snippets:

  • Looping over an object’s keys and values
  • Get all direct descendant elements that match a test
  • Get an attribute on an element
  • Insert an HTML string after the end of the specified element

Primary Sidebar

FREE UPDATES!

Get the latest updates in your inbox for FREE!

Popular Posts

Story Generator

IP Grabber

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2022 JavaScriptSource.com

  • About
  • Privacy Policy
  • Submit
  • FAQ
  • Jobs For Developers
  • Contact Us