convert an array to other array

Convert an array to other array

Converting an array to another array means creating a new array from an existing array with modifications or changes. There are different ways to achieve this, depending on the programming language and specific requirements.

Using map() function

The map() function is a built-in method in JavaScript that creates a new array by calling a provided function on each element of the original array. The provided function can modify the elements as needed.


const originalArray = [1, 2, 3, 4, 5];
const modifiedArray = originalArray.map(element => element * 2);
console.log(modifiedArray); // [2, 4, 6, 8, 10]

The above code creates a new array by multiplying each element of the original array by 2. The result is stored in the modifiedArray variable.

Using filter() function

The filter() function is another built-in method in JavaScript that creates a new array by filtering elements from the original array based on a provided condition. The condition should return true or false for each element.


const originalArray = [1, 2, 3, 4, 5];
const filteredArray = originalArray.filter(element => element % 2 === 0);
console.log(filteredArray); // [2, 4]

The above code creates a new array by filtering out odd numbers from the original array. The result is stored in the filteredArray variable.

Using slice() function

The slice() function is a built-in method in JavaScript that creates a new array by extracting a portion of the original array. The portion is specified by the start and end indexes. The end index is optional and defaults to the length of the array.


const originalArray = [1, 2, 3, 4, 5];
const slicedArray = originalArray.slice(1, 4);
console.log(slicedArray); // [2, 3, 4]

The above code creates a new array by extracting elements from the original array between the indexes 1 and 4 (exclusive). The result is stored in the slicedArray variable.

Using concat() function

The concat() function is a built-in method in JavaScript that creates a new array by concatenating two or more arrays. The original arrays are not modified.


const originalArray1 = [1, 2];
const originalArray2 = [3, 4];
const concatenatedArray = originalArray1.concat(originalArray2);
console.log(concatenatedArray); // [1, 2, 3, 4]

The above code creates a new array by concatenating two original arrays into one. The result is stored in the concatenatedArray variable.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe