array-custom-methods

1.0.6 • Public • Published

Array Custom Methods

array-custom-methods

A package that extends JavaScript arrays with additional useful methods.

Installation

npm install array-custom-methods

Usage

require('array-custom-methods');

Custom Array Methods

1. myMap(callback)

A custom implementation of map that applies a callback to each element.

Example:

const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.myMap(num => num * 2);
console.log(doubled); // Output: [2, 4, 6, 8, 10]

2. myForEach(callback)

A custom implementation of forEach that executes a callback for each element.

Example:

const fruits = ['apple', 'banana', 'cherry'];
fruits.myForEach((fruit, index) => {
    console.log(`${index}: ${fruit}`);
});

3. myFilter(callback)

A custom implementation of filter that returns elements that pass the test.

Example:

const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.myFilter(num => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4]

4. myReduce(callback, initialVal)

A custom implementation of reduce that accumulates values.

Example:

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.myReduce((acc, curr) => acc + curr, 0);
console.log(sum); // Output: 15

5. revArray()

Reverses the array without modifying the original.

Example:

const numbers = [1, 2, 3, 4, 5];
const reversed = numbers.revArray();
console.log(reversed); // Output: [5, 4, 3, 2, 1]

6. myPush(...elements)

A custom implementation of push.

Example:

const fruits = ['apple', 'banana'];
const newLength = fruits.myPush('cherry', 'date');
console.log(fruits); // Output: ['apple', 'banana', 'cherry', 'date']
console.log(newLength);  // Output: 4

7. sum()

Returns the sum of numeric elements.

Example:

const numbers = [10, 20, 30];
console.log(numbers.sum()); // Output: 60

8. prod()

Returns the product of numeric elements.

Example:

const numbers = [2, 3, 4];
console.log(numbers.prod()); // Output: 24

9. average()

Returns the average of numeric elements.

Example:

const numbers = [10, 20, 30];
console.log(numbers.average()); // Output: 20

10. removeDuplicates()

Removes duplicate elements.

Example:

const numbers = [1, 2, 2, 3, 4, 4, 5];
console.log(numbers.removeDuplicates()); // Output: [1, 2, 3, 4, 5]

11. hashMapOfArray()

Transforms the array into a Map.

Example:

const fruits = ['apple', 'banana', 'cherry'];
console.log(fruits.hashMapOfArray()); // Output: Map { 0 => 'apple', 1 => 'banana', 2 => 'cherry' }

Dependents (0)

Package Sidebar

Install

npm i array-custom-methods

Weekly Downloads

3

Version

1.0.6

License

ISC

Unpacked Size

6.83 kB

Total Files

3

Last publish

Collaborators

  • bantisingh97