Here is a summary of some major array functions with examples in JavaScript.
Code snippet to define an example of an array
var persons = new Array(); var object = { name: "Mary", age:22, email: "mary@gmail.com"}; persons.push(object); object = { name: "Jack", age:25, email: "jack@gmail.com"}; persons.push(object); object = { name: "Bob", age:37, email: "bob@gmail.com"}; persons.push(object);
Function | Definition | Result Type | Code Snippet | Code Output |
filter | Gets the elements satisfying the testing function |
|
| [{name: 'Mary', age: 22, email: 'mary@gmail.com'}, {name: 'Jack', age: 25, email: 'jack@gmail.com'}] |
map |
| Array |
| ['Mary', 'Jack', 'Bob'] |
join | Concatenates all array elements as a string with a separator | String |
| Mary, Jack, Bob |
find | Returns the first element satisfying the testing function | object |
console.log(first_found); | {name: 'Mary', age: 22, email: 'mary@gmail.com'} |
| number | const first_index = persons.findIndex(p => p.age > 25); console.log(first_index); | 2 | |
reduce | Reduces array elements to a single value after applying a custom function | It depends on the single value you want to get like number, string, etc. | const initAge = 0; const sumAges = persons.reduce( (accumulator, currentPerson) => accumulator + currentPerson.age, initAge, ); const meanAge = Math.round(sumAges/persons.length); console.log(meanAge); | 28 |
No comments:
Post a Comment