arrays in javascript are like containers that can hold different types of data, such as numbers, strings, booleans, objects, functions, and even other arrays. let's delve into some key methods used for manipulating arrays: forEach
, map
, filter
, find
, and indexOf
.
forEach
the forEach
method is used to perform an operation on each element of an array. for example:
var arr = [1, 2, 3, 4];
arr.forEach(function (val) {
console.log(val + " Hello");
});
// Output:
// 1 Hello
// 2 Hello
// 3 Hello
// 4 Hello
map
the map
method creates a new array by applying a function to each element of the original array. it returns a new array of the same size. here are some examples:
var arr = [1, 2, 3, 4];
// Case I:
var newarr = arr.map(function (val) {
return 13;
});
// Output: [13, 13, 13, 13]
// Case II:
var newarr = arr.map(function (val) {
return val;
});
// Output: [1, 2, 3, 4]
// Case III:
var newarr = arr.map(function (val) {
return val * 3;
});
// Output: [3, 6, 9, 12]
filter
the filter
method is used to create a new array with elements that pass a certain condition. it's similar to map
but returns a subset of the original array.
var arr = [1, 2, 3, 4];
var newarr = arr.filter(function (val) {
if (val >= 3) return true;
});
// Output: [3, 4]
find
the find
method is used to locate the first occurrence of an element in an array. it returns the value of the first element that satisfies the provided testing function.
var arr = [1, 2, 3, 3, 4];
var newarr = arr.find(function (val) {
if (val === 3) return val;
});
// Output: 3
// Only the first matching value is returned
indexOf
the indexOf
method helps find the index of a specified element in an array. it returns -1
if the element is not found.
var arr = [1, 2, 3, 4];
var index = arr.indexOf(3);
// Output: 2
understanding these array methods will empower you to efficiently manipulate arrays in javascript for various tasks. happy coding!