Javascript array map index

JavaScript map with index [SOLVED]

Higher-order functions take other functions as arguments and/or return a function value, and in JavaScript, we have built-in higher-order functions such as filter , reduce , and map which are available based on the array prototype.

However, our focus is on the map function which allows us to create a new array by applying a callback function on every element in the array it’s called on. In this article, we will discuss how map works and how to work with map with index.

How JavaScript Map Works

As stated, map creates or returns a new array after the effects of a callback function have been done on an array’s elements.

Let’s illustrate how map works by changing the elements of an array by either multiplying them or adding the string “added” if the element is a Number or String . In the illustration, the map function takes a single callback function (an arrow function), and this arrow function takes one argument (the element at every iterative instance) and as within its function body the conditional logic that applies the necessary action on the element depending on their type .

const arr = [12, 34, "one", "two", 56, "four"]; const arrOptimized = arr.map((x) => < if (typeof x === "string") < return x + "added"; >else if (typeof x === "number") < return x * 2; >>); console.log(arrOptimized); 
[ 24, 68, 'oneadded', 'twoadded', 112, 'fouradded' ]

Also, remember that the map function doesn’t change the content of the array it is applied on, it only returns a new array.

Читайте также:  Html and php templates

JavaScript Map With Index

Now, if we need to have access to the index of each element when using the map function, it is fairly easy to access it. For the example in the previous section, the callback function took only one argument — the element — which is required. We can take other arguments which are optional, and the index argument is one such.

Therefore, if we need the index , we can add a new argument to our callback function and make use of the argument. Using the same illustration as in the previous section, we can log an updated statement with the index position.

const arr = [12, 34, "one", "two", 56, "four"]; const arrOptimized = arr.map((x, y) => < if (typeof x === "string") < console.log(`Element "$" of the index $ has been optimized`); return x + "added"; > else if (typeof x === "number") < console.log(`Element "$" of the index $ has been optimized`); return x * 2; > >); console.log(arrOptimized); 
Element 12 of the index 0 has been optimized Element 34 of the index 1 has been optimized Element "one" of the index 2 has been optimized Element "two" of the index 3 has been optimized Element 56 of the index 4 has been optimized Element "four" of the index 5 has been optimized [ 24, 68, 'oneadded', 'twoadded', 112, 'fouradded' ]

The x and y bindings represent the element and the index of the said element at every iterative instance.

Summary

To work with map is an interesting approach, especially with composability, and if you need access to the index of the element within the map , you can make use of the second argument that’s optional for your callback function. With that, map with index is possible and easy to use.

References

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment Cancel reply

JavaScript Tutorial

  • Beginner Guide
    • Define Global Variable
    • Working with Object Literals
    • Working with Template Literals
    • Classes Overview
    • Subclass Examples
    • Iterators and Generators
    • Error Handling
    • Date Formatting
    • parseFloat()
    • Array.pop()
    • Array.slice()
    • Array.unshift()
    • Array.join()
    • Array.findIndex()
    • Array Slicing Methods
    • Remove Element from Array
    • Check Array is Empty
    • Create Unique Array of Objects
    • Convert Array to String
    • String.toLowerCase()
    • String.toString()
    • String.trimEnd()
    • String.trim()
    • String.replaceAll()
    • String.startsWith()
    • replaceWith()
    • String.indexOf()
    • replaceAll() with regex
    • Check if String is Number
    • Check string contains spaces
    • Convert String to Boolean
    • Check String contains Substring
    • Compare Strings
    • Math.acos()
    • Math.abs()
    • Math.asin()
    • Math.atan()
    • Math.cbrt()
    • Math.ceil()
    • Math.cos()
    • Math.floor()
    • Math.fround()
    • Math.hypot()
    • Math.log()
    • Math max()
    • Math.power()
    • Math.random()
    • Math.toRadians()
    • Nested Function
    • Arrow Function
    • Optional Parameters
    • The arguments Object
    • Calling Vs Invoking a Function
    • Call a function every second
    • Using function as Values
    • Chaining Functions
    • if statement
    • Handling Special Characters
    • hide() Method
    • Set.add()
    • Remove Element from Set
    • DOM Selector Methods
    • Find Elements in DOM
    • Remove DOM Element
    • Replace DOM Element
    • Get DOM Element Width
    • addEventListener()
    • querySelector()
    • getBoundingClientRect()
    • NodeList
    • Node.insertBefore()
    • Event Bubbling
    • Parse JSON File
    • Parse YAML File
    • Parse CSV File
    • async function
    • await
    • Exponentiation (**)
    • Bitwise XOR (^)
    • Nullish Coalescing Operator (??)
    • Double Exclamation Mark (!!)
    • Spread Operator (. )
    • Destructuring assignment
    • instanceof Operator
    • Access map with index
    • Check map size
    • Sort map by value
    • Sort by date
    • Add days to date
    • date/time field value out of range
    • Promise Thenable Object
    • Promise.all()
    • Promise.resolve()
    • Promise.race()
    • Promise.reject()
    • Chaining Promises
    • Keyboard Events
    • Mouse Events
    • Singleton Pattern
    • Mediator Pattern
    • Observer Pattern
    • Factory Pattern

    Источник

    Array.prototype.map()

    The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

    Try it

    Syntax

    map(callbackFn) map(callbackFn, thisArg) 

    Parameters

    A function to execute for each element in the array. Its return value is added as a single element in the new array. The function is called with the following arguments:

    The current element being processed in the array.

    The index of the current element being processed in the array.

    The array map() was called upon.

    A value to use as this when executing callbackFn . See iterative methods.

    Return value

    A new array with each element being the result of the callback function.

    Description

    The map() method is an iterative method. It calls a provided callbackFn function once for each element in an array and constructs a new array from the results.

    callbackFn is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays.

    The map() method is a copying method. It does not alter this . However, the function provided as callbackFn can mutate the array. Note, however, that the length of the array is saved before the first invocation of callbackFn . Therefore:

    • callbackFn will not visit any elements added beyond the array’s initial length when the call to map() began.
    • Changes to already-visited indexes do not cause callbackFn to be invoked on them again.
    • If an existing, yet-unvisited element of the array is changed by callbackFn , its value passed to the callbackFn will be the value at the time that element gets visited. Deleted elements are not visited.

    Warning: Concurrent modifications of the kind described above frequently lead to hard-to-understand code and are generally to be avoided (except in special cases).

    The map() method is generic. It only expects the this value to have a length property and integer-keyed properties.

    Since map builds a new array, calling it without using the returned array is an anti-pattern; use forEach or for. of instead.

    Examples

    Mapping an array of numbers to an array of square roots

    The following code takes an array of numbers and creates a new array containing the square roots of the numbers in the first array.

    const numbers = [1, 4, 9]; const roots = numbers.map((num) => Math.sqrt(num)); // roots is now [1, 2, 3] // numbers is still [1, 4, 9] 

    Using map to reformat objects in an array

    The following code takes an array of objects and creates a new array containing the newly reformatted objects.

    const kvArray = [  key: 1, value: 10 >,  key: 2, value: 20 >,  key: 3, value: 30 >, ]; const reformattedArray = kvArray.map(( key, value >) => ( [key]: value >)); console.log(reformattedArray); // [< 1: 10 >, < 2: 20 >, < 3: 30 >] console.log(kvArray); // [ // < key: 1, value: 10 >, // < key: 2, value: 20 >, // // ] 

    Mapping an array of numbers using a function containing an argument

    The following code shows how map works when a function requiring one argument is used with it. The argument will automatically be assigned from each element of the array as map loops through the original array.

    const numbers = [1, 4, 9]; const doubles = numbers.map((num) => num * 2); console.log(doubles); // [2, 8, 18] console.log(numbers); // [1, 4, 9] 

    Calling map() on non-array objects

    The map() method reads the length property of this and then accesses each property whose key is a nonnegative integer less than length .

    const arrayLike =  length: 3, 0: 2, 1: 3, 2: 4, 3: 5, // ignored by map() since length is 3 >; console.log(Array.prototype.map.call(arrayLike, (x) => x ** 2)); // [ 4, 9, 16 ] 

    Using map() generically on a NodeList

    This example shows how to iterate through a collection of objects collected by querySelectorAll . This is because querySelectorAll returns a NodeList (which is a collection of objects).

    In this case, we return all the selected option s’ values on the screen:

    const elems = document.querySelectorAll("select option:checked"); const values = Array.prototype.map.call(elems, ( value >) => value); 

    An easier way would be the Array.from() method.

    Using map() on sparse arrays

    A sparse array remains sparse after map() . The indices of empty slots are still empty in the returned array, and the callback function won’t be called on them.

    .log( [1, , 3].map((x, index) =>  console.log(`Visit $index>`); return x * 2; >), ); // Visit 0 // Visit 2 // [2, empty, 6] 

    Using parseInt() with map()

    It is common to use the callback with one argument (the element being traversed). Certain functions are also commonly used with one argument, even though they take additional optional arguments. These habits may lead to confusing behaviors.

    While one might expect [1, 2, 3] , the actual result is [1, NaN, NaN] .

    parseInt is often used with one argument, but takes two. The first is an expression and the second is the radix to the callback function, Array.prototype.map passes 3 arguments:

    The third argument is ignored by parseInt —but not the second one! This is the source of possible confusion.

    Here is a concise example of the iteration steps:

    // parseInt(string, radix) -> map(parseInt(value, index)) /* first iteration (index is 0): */ parseInt("1", 0); // 1 /* second iteration (index is 1): */ parseInt("2", 1); // NaN /* third iteration (index is 2): */ parseInt("3", 2); // NaN 

    Then let’s talk about solutions.

    const returnInt = (element) => parseInt(element, 10); ["1", "2", "3"].map(returnInt); // [1, 2, 3] // Actual result is an array of numbers (as expected) // Same as above, but using the concise arrow function syntax ["1", "2", "3"].map((str) => parseInt(str)); // [1, 2, 3] // A simpler way to achieve the above, while avoiding the "gotcha": ["1", "2", "3"].map(Number); // [1, 2, 3] // But unlike parseInt(), Number() will also return a float or (resolved) exponential notation: ["1.1", "2.2e2", "3e300"].map(Number); // [1.1, 220, 3e+300] // For comparison, if we use parseInt() on the array above: ["1.1", "2.2e2", "3e300"].map((str) => parseInt(str)); // [1, 2, 3] 

    One alternative output of the map method being called with parseInt as a parameter runs as follows:

    const strings = ["10", "10", "10"]; const numbers = strings.map(parseInt); console.log(numbers); // Actual result of [10, NaN, 2] may be unexpected based on the above description. 

    Mapped array contains undefined

    When undefined or nothing is returned:

    const numbers = [1, 2, 3, 4]; const filteredNumbers = numbers.map((num, index) =>  if (index  3)  return num; > >); // index goes from 0, so the filterNumbers are 1,2,3 and undefined. // filteredNumbers is [1, 2, 3, undefined] // numbers is still [1, 2, 3, 4] 

    Specifications

    Browser compatibility

    BCD tables only load in the browser

    See also

    Found a content problem with this page?

    This page was last modified on Jun 27, 2023 by MDN contributors.

    Your blueprint for a better internet.

    Источник

Оцените статью