What do the three dots "..." do in JavaScript [duplicate] - javascript

This question already has answers here:
Javascript Property with three dots (...)
(5 answers)
What does this symbol mean in JavaScript?
(1 answer)
Closed 2 years ago.
I have gone through the following JavaScript code:
let num = [1,2,2,2,3,4,5];
console.log([... new Set(nums)]); //which prints [1,2,3,4,5]
I did not understand what this ... device (three dots) does in this example.

I think you need to read Iteration first;
let nums = [1,2,2,2,3,4,5];
let setFromArray = new Set(nums);
let arrayFromSet_spread = [...setFromArray];
console.log("spread", arrayFromSet_spread);
// here the spread will iterate over iteratable and return current value
//arrayFromSet can be written without spread like this
let arrayFromSet_forOf = [];
for ( let el of setFromArray ) {
arrayFromSet_forOf.push(el)
}
console.log("forOf",arrayFromSet_forOf);
// and the most naive way to iterate :)
let arrayFromSet_ManualIteration = [];
let setFromArrayIterator = setFromArray[Symbol.iterator]();
const firstElement = setFromArrayIterator.next();
const secondElement = setFromArrayIterator.next();
const thirdElement = setFromArrayIterator.next();
const fourthElement = setFromArrayIterator.next();
const fifthElement = setFromArrayIterator.next();
const sixthElement = setFromArrayIterator.next();
arrayFromSet_ManualIteration.push(firstElement);
arrayFromSet_ManualIteration.push(secondElement);
arrayFromSet_ManualIteration.push(thirdElement);
arrayFromSet_ManualIteration.push(fourthElement);
arrayFromSet_ManualIteration.push(fifthElement);
arrayFromSet_ManualIteration.push(sixthElement);
//you could just push values not the itaration object itself
//arrayFromSet_ManualIteration.push(firstElement.value);
//arrayFromSet_ManualIteration.push(secondElement.value);
//arrayFromSet_ManualIteration.push(thirdElement.value);
//arrayFromSet_ManualIteration.push(fourthElement.value);
//arrayFromSet_ManualIteration.push(fifthElement.value);
console.log('ManualIteration full objects',arrayFromSet_ManualIteration);

Related

Create array with many arrays inside which are created from one big array on special condition [duplicate]

This question already has answers here:
Transposing a 2D-array in JavaScript
(25 answers)
Closed 2 years ago.
// n number of those
let array1 = [1,3,3,6]
let array2 = [4,7,3,8]
let array3 = [1,4,6,4]
// wanted
let final = [
[1,4,1], <-- first array in the final
[3,7,4],
[3,3,6],
[6,8,4]
]
First from each array (array1, array2, array3...) create first array in final one.
Second from each array create second one.. etc.
Any ideas?
You can do something like this:
const final = [];
for (let i = 0; i < array1.length; ++i) {
final[i] = [array1[i], array2[i], array3[i]];
}
console.dir(final);
you can try this
let array1 = [1,3,3,6]
let array2 = [4,7,3,8]
let array3 = [1,4,6,4]
finarray=[]
array1.forEach((x,i)=>{ finarray.push([x,array2[i],array3[i]])})
console.log(finarray)

How to get a random key value from a JavaScript object [duplicate]

This question already has answers here:
Pick random property from a Javascript object
(9 answers)
Get array of object's keys
(8 answers)
Closed 2 years ago.
I have a Javascript hash of Spanish words/phrases and their English meanings:
let phrases = {
hola: "hello",
adios: "bye",
};
I want to select a random key. I have tried for a while, and my latest attempt hasn't worked and returns undefined:
var keys = phrases.keys;
var len = phrases.length;
var rnd = Math.floor(Math.random()*len);
var key = phrases[rnd];
I've looked at other Stack Overflow answers but can't seem to find exactly what I'm looking for. Any ideas please?
Probably you can use Object.keys() instead.
Try the following:
const phrases = {
hola: "hello",
adios: "bye",
};
const keys = Object.keys(phrases);
const len = keys.length;
const rnd = Math.floor(Math.random() * len);
const key = phrases[keys[rnd]];
console.log(key);
I hope this helps!

Add a prefix to all the element of an array of strings using javascript without iteration(.map() or loops) [duplicate]

This question already has answers here:
How to add prefix to array values?
(5 answers)
Closed 4 years ago.
Input: The Array of the strings
var arr = ['a','b','c'];
var prefix = 'prefix_';
Output: Each element in the array should be prefixed by 'prefix':
['prefix_a','prefix_b','prefix_c']
You just need to use Array.prototype.map here, it transforms each element of the array based on the callback method.
var arr = ['a','b','c'];
var prefix = 'prefix_';
var newArr = arr.map(el => prefix + el);
console.log(newArr);
A simpler, ES6 way using Array#map :
const prefixArray = (array, prefix) => array.map(e => prefix+e);
Demo:
let arr = ['a','b','c'];
const prefix = 'prefix_';
const prefixArray = (array, prefix) => array.map(e => prefix+e);
console.log(prefixArray(arr,prefix));

Declaring variables using an array [duplicate]

This question already has answers here:
Multiple assignment in JavaScript? What does `[ a, b, c ] = [ 1, 2, 3 ]` mean?
(4 answers)
Closed 4 years ago.
I came across this code in JS Novice to Ninja.
const form = document.getElementsByTagname('form')[0];
const [input,button] = form.elements;
this create a const called input mapped to the value of the form[0]
and another const called button mapped to form[1]
is this:
const [input,button] = form.elements;
the same as:
const input = form.elements[0];
const button = form.elements[1];
Is that just some shorthand I've never come across? If so can someone tell me what it's called? Or am I misunderstanding what is happening here.
const [input,button] = form.elements;
would actually be the same as
const input = form.elements[0];
const button = form.elements[1];
This is called destructuring and it can also be used for objects.
const {value} = someObject;
would be the same as const value = someObject.value;

random and different values when using the Array function “fill” [duplicate]

This question already has answers here:
Creating array of length n with random numbers in JavaScript
(6 answers)
Closed 5 years ago.
const array = new Array(10);
array.fill('hi');
console.log(array);
Using Array::fill to populate a value on the whole array or part of the array.
I have a string generator function that generates a random string.
const getString = () => Math.random().toString(36).replace(/[^a-z]+/g, '');
console.log(getString())
console.log(getString())
console.log(getString())
I want to fill the array with different values by executing the string generator function each time .
It cannot done by one line in fill , however, I found a workaround leveraging the signature of fill : arr.fill(value[, start = 0[, end = this.length]])
const getString = () => Math.random().toString(36).replace(/[^a-z]+/g, '');
const array = new Array(10);
for (var i=0; i < array.length;i++ ) {
array.fill(getString(), i, i + 1);
}
console.log(array);
Does fill supports callbacks that can be executed each iteration to generate different values ?
If no, what is the alternative ?
We can reach the same result in one line combining map and fill :
array.fill().map(getString)
const getString = () => Math.random().toString(36).replace(/[^a-z]+/g, '');
const array = new Array(10);
console.log(array.fill().map(getString))

Categories

Resources