Javascript Array.from()

0
158
Javascript
Javascript

Javascript Array.from() is a javascript array method that creates a new, shallow-copied Array instance from an array-like or iterable object.

See Examples:

<script>
function Shopinson(){
	document.getElementById("result").innerHTML = Array.from('WebArt');
}
</script>
<p id="result"></p>
<button type="button" onClick="Shopinson()">Click Run</button>

the result will be like this W,e,b,A,r,t

This Javascript Array Method just explode a string text and include a seperator in between characters

Another interesting example of Javascript Array.from

this examples is based on the mozilla developers since as of the time I wrote this w3 have not article yet on this topic

<script>
function Shopinson(){
	document.getElementById("result").innerHTML = Array.from([1, 2, 3], x => x + x);
}
</script>
<p id="result"></p>
<button type="button" onClick="Shopinson()">Click Run</button>

Syntax of Javascript Array.from()

Array.from(arrayLike [, mapFn [, thisArg]])

the parameters in the syntax of the javascript array is well established in the second example above.

According to mozilla developer this below syntax of .from() array method produces same result but second syntax does not create an intermediate array.

  1. Array.from(obj, mapFn, thisArg)
  2. Array.from(obj).map(mapFn, thisArg),

Other examples

using a set

<script>
var Godwin = new Set(['education', 'blog', 'philanthropist', 'design']);
function Shopinson(){
	document.getElementById("result").innerHTML = Array.from(Godwin);
}
</script>
<p id="result"></p>
<button type="button" onClick="Shopinson()">Click Run</button>

Using Map

<script>
var Godwin = new Map([[1, 2], [2, 4], [4, 8]]);
function Shopinson(){
	document.getElementById("resulta").innerHTML = Array.from(Godwin);
	document.getElementById("resultb").innerHTML = Array.from(Godwin.values());
	document.getElementById("resultc").innerHTML = Array.from(Godwin.keys());
}
</script>
<p id="resulta"></p>
<p id="resultb"></p>
<p id="resultc"></p>
<button type="button" onClick="Shopinson()">Click Run</button>

Array from an Array-like object (arguments)

<script>
function Godwin(){
	return Array.from(arguments)
}
function Shopinson(){
	document.getElementById("result").innerHTML = Godwin('Volvo', 'Corolla', 'Yamaha');
}
</script>
<p id="result"></p>
<button type="button" onClick="Shopinson()">Click Run</button>

Using arrow functions and Array.from()

<script>
function Shopinson(){
	document.getElementById("result").innerHTML = Array.from({length: 5}, (v, i) => i);
}
</script>
<p id="result"></p>
<button type="button" onClick="Shopinson()">Click Run</button>

LEAVE A REPLY

Please enter your comment!
Please enter your name here