ES6 in Depth
  • Introduction
  • Installation
  • Block Scope
    • Constant
    • Use cases
  • Template String
    • New String Methods
    • Tagged Template Literal
  • New Number Methods
  • Arrow Function
    • Default Parameters
    • Lexical This Scope
    • Where not to use arrow function
  • Object Enhancement
  • New Array Methods
    • For Of
  • Spread Operator
  • Destructuring
    • Array Destructuring
  • Class
  • Symbols
  • New Data Structures
    • Set
    • Map
    • WeakSet
    • WeakMap
    • Iterators
    • Generators
  • Promise
  • Import Export
Powered by GitBook
On this page
  • Static methods
  • Array.of
  • Array.from
  • Array.from use case 1
  • Array.from use case 2
  • Array instance methods
  • [].find
  • [].findIndex()
  • [].copyWithin()

Was this helpful?

New Array Methods

Static methods

Array.of
Array.from

Array.of

var arr = Array(4); // arr.length = 4
var arr1 = Array.of(4); // arr1.length = 1 

// create array from the passed arguments
console.log(Array.of(2,3,4,5)); // [2,3,4,5]

Array.from

want to use Array methods on arguments

// ES5
function greetMe(){
    console.log(arguments.join('--')); // TypeError: arguments.join is not a function
}

console.log(greetMe('hemant', "hello"));
// ES6
function greetMe(){
    console.log(Array.from(arguments).join('--')); // hemant--hello
}

console.log(greetMe('hemant', "hello"));

Array.from use case 1

var paragraphs = document.querySelector('p');

paragraphs.map() // Error

var paragraphsArray = Array.from(paragraphs);
// now you can use map on it

// Array.from also have map as 2nd argument
Array.from(paragraphs, person => person.textContent);

Array.from use case 2

// Loop over arguments
function sum(){
    return Array.from(arguments).reduce((prev, next) => prev+next, 0);
}

console.log(sum(1,2,3,4,4,456,6));

Array instance methods

[].find()
[].findIndex()
[].copyWithin()

[].find

var arr = [
    { name: "hemant", age: 30},
    { name: "Vinay", age: 20},
    { name: "Varun", age: 88}
];

var myName = arr.find(function(item){
    return item.name === 'Varun';
});

console.log(myName); // { name: "Varun", age: 88}

[].findIndex()

var arr = [
    { name: "hemant", age: 30},
    { name: "Vinay", age: 20},
    { name: "Varun", age: 88}
];

    return item.name === 'Varun';
});
var indexOfName = arr.findIndex(function(item){

console.log(indexOfName); // 2

[].copyWithin()

var arr = [
    { name: "hemant", age: 30},
    { name: "Vinay", age: 20},
    { name: "Varun", age: 88}
];

console.log(arr.copyWithin(2, 0));
// output
[
    { name: "hemant", age: 30},
    { name: "Vinay", age: 20},
    { name: "hemant", age: 30}
]
PreviousObject EnhancementNextFor Of

Last updated 4 years ago

Was this helpful?