Home  >  Article  >  Web Front-end  >  #eetcode Apply Transform Over Each Element in Array

#eetcode Apply Transform Over Each Element in Array

WBOY
WBOYOriginal
2024-08-16 06:05:32318browse

#eetcode Apply Transform Over Each Element in Array

Given an integer array arr and a mapping function fn, return a new array with a transformation applied to each element.

The returned array should be created such that returnedArray[i] = fn(arr[i], i).

Please solve it without the built-in Array.map method.

Example 1:

Input: arr = [1,2,3], fn = function plusone(n) { return n + 1; }
Output: [2,3,4]
Explanation:
const newArray = map(arr, plusone); // [2,3,4]
The function increases each value in the array by one.

Example 2:

Input: arr = [1,2,3], fn = function plusI(n, i) { return n + i; }
Output: [1,3,5]
Explanation: The function increases each value by the index it resides in.

Example 3:

Input: arr = [10,20,30], fn = function constant() { return 42; }
Output: [42,42,42]
Explanation: The function always returns 42.

Constraints:

  • 0 <= arr.length <= 1000
  • -10^9 <= arr[i] <= 10^9
  • fn returns a number

Solution

/**
 * @param {number[]} arr
 * @param {Function} fn
 * @return {number[]}
 */
var map = function (arr, fn) {
    let newArr = [];

    for (let i = 0; i < arr.length; i++) {
        newArr[i] = fn(arr[i], i);
    }
    return newArr;
};

Code walkthrough

var map = function (arr, fn) {
This is the function declaration. The map function takes in tow arguments, arr(an array of numbers), and fn(a function that will be applied to each element of the array).

let newArr = [];
Create an empty array to store the transformed array elements.

for (let i = 0; i < arr.length; i++)
Loop through the entire input array arr

newArr[i] = fn(arr[i], i);
Checks whether every array element in arr[i] meets the specified condition and stores the result in the empty array newArr

return newArr;
Returns the newly created array containing the transformed elements.

The above is the detailed content of #eetcode Apply Transform Over Each Element in Array. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn