how square brackets works in map function javascript? [duplicate] - javascript

This question already has answers here:
Square brackets surrounding parameter in function definition
(3 answers)
Closed 4 years ago.
var a = {a:{bb:"mm"},b:{bbb:"bb"}}
var v= Object.entries(a)
// a print array items value that is fine
v.map((a,b)=>{console.log(a)})
// print the index that is fine
v.map((a,b)=>{console.log(b)})
// why it print
//
//{bb: "mm"}
//{bbb: "bb"}
v.map(([a,b])=>{console.log(b)})
//output
https://jsbin.com/zevuqedupa/edit?html,js,console,output ..why not print index
Hi
my question why it is printing in object.Is it destructing of es2015? is it es6 part ?

The Object.entries(..) method accepts an object and returns an array of key-value pairs, that are other arrays where the first element is the key and the second element is the value.
In this case, the v variable will be:
[['a', {bb: 'mm'}], ['b', {bbb: 'bb'}]];
The map method will iterate on each of the inner array.
So, on the first iteration it will receive, as first parameter:
['a', {bb: 'mm'}]
On the second iteration ti will receive, as first parameter:
['b', {bbb: 'bb'}]
Now we go to destructuring. When you pass the square brackets in the first parameter, you say:
Hey, the first parameter will be an array, let a be the first element of the array and let b be the second element of the array.
You print b, so you print the second element of the array at each iteration, and that is the value.
If you want, you can also print the index, since [a, b] is the first parameter altogether.
v.map(([a,b], index) => {console.log(`value: ${b}, index: ${index}`)})

(a,b)=>{console.log(b)}
Expects 2 parameters named a and b and is called like f(a,b);
([a,b])=>{console.log(b)}
Expects and array and names the 0 and 1 indexes a and b and is called like f([a,b])

Related

Is there a way to splice out elements of an array and return the spliced array in one line? [duplicate]

This question already has answers here:
Js remove element from array without change the original
(4 answers)
Closed 13 days ago.
If I have an array a = [1,2,3,4] and I want to return it with the 3 removed, there are two ways I can do it:
let b = [...a] // or a.slice()
b.splice(2,1)
return b
or
return [...a.slice(0,2), ...a.slice(3,4)]
Advantage of the second is that it's one line. Disadvantage is that it's verbose. I thought of writing a helper function that contains the logic of the first approach, so that I'd be able to call it in one line elsewhere.
Is there an alternative? Something like splice but that returns that spliced array rather than mutating it and returning the spliced-out elements.
Since you know the indicies you want to remove, you can use the Array.prototype.filter method.
const a = [1,2,3,4];
const b = a.filter((_, i) => i !== 2);
console.log(b);
If you need to remove a range, you can just do something like 2 < i || i > 3.
.filter makes a copy of the array, copying the values where the callback function evaluates truthy and ignores the values where the callback function evaluates falsy.

Creating array of arrays different behavior [duplicate]

This question already has answers here:
Array.fill(Array) creates copies by references not by value [duplicate]
(3 answers)
Closed 6 years ago.
I have found that these two different methods of creating an array of arrays produce different behaviors:
// Method 1
for (var arr1 = []; arr.push([]) < len;) {}
// Method 2
var arr2 = new Array(len).fill([])
The arrays created look the same in the console, however they behave differently in my code. What could be causing this?
The difference is that in the 1st method each index points to a different array, while in the Array#fill all indexes point to the same array.
Note: the 1st method will not create an array of arrays
var len = 3;
var arr1 = [];
// Method 1
for (var arr1 = []; arr1.push([]) < len;) {} // new sub array is pushed into arr1
// Method 2
var arr2 = new Array(len).fill([]) // each place in the array is filled with a reference to the same array
arr1[0].push(1); // push to the 1st element of arr1
arr2[0].push(1); // push to the 1st element of arr2
console.log('arr1: ', JSON.stringify(arr1)); // only the 1st sub array contains 1
console.log('arr2: ', JSON.stringify(arr2)); // all sub arrays contain 1
Update: While the answer below is technically accurate, and is another difference between the two methods, #Ori Drori's answer is almost certainly what the OP is looking for.
I'll take a stab at this, but more context would be helpful.
In common practice, these two statements typically behave the same, but there is a key difference - when you use the new keyword, the Javascript interpreter calls the Array constructor.
If you were to overwrite the Array constructor, this would only apply to arr2 which was defined with the new keyword. arr1 created with the array literal would still be a Javascript array.
As an example, let's say I wrote the following code:
function Array() {
}
Method 1 would still work, but Method 2 would return a TypeError indicating that fill is not a function.
Interestingly, using the Array literal (Method 1) still calls the Array constructor, so if I did a console.log("test"); within the Array construction this would still be printed to the console when using either method. BUT, when the Array literal (Method 1) is used, the object itself still remains a standard Javascript array even if the Array constructor is overwritten.

Why pushing undefined to an empty array give 1? [duplicate]

This question already has answers here:
Why does Array.prototype.push return the new length instead of something more useful?
(6 answers)
Closed 4 months ago.
If I do
var a = [].push(undefined);
console.log(a);
it gives output as 1 even though undefined was pushed to the array. Any idea why?
You're testing it the wrong way. a is not defined as the array, as I think you suppose it to be. Try this:
var a = []
a.push(undefined);
console.log(a);
You are assigning the return value of push function to variable a. push returns the length of the array after pushing the current element in context. So, it returns 1 after pushing undefined in the array.
its pushing the length of array inside not the elements
example
var a = [].push(5,6,7,8);
console.log(a); //gives 4
Push returns the new length of the array, and thats what is stored in a
There was no explicit check has been done when assigning a new property to array object. Assigning a new property in the sense, setting 0,1,2..n properties with values, based on the length of the array.
Repeat, while items is not empty
Remove the first element from items and let E be the value of the element.
Let setStatus be Set(O, ToString(len), E, true).
ReturnIfAbrupt(setStatus).
Let len be len+1.
You can see it here. Step 8.

JavaScript property accessors wrapped in array [duplicate]

This question already has answers here:
Why does 2 == [2] in JavaScript?
(9 answers)
Closed 6 years ago.
I'm failing to find documentation as to how/why the following works:
const data = {one: 1, two: 2}
const key = ['one']
data[key[0]] // 1
data[key] // 1
data[[key]] // 1
data[[[key]]] // 1
data[[[[key]]]] // 1
data[['one', 'two']] // undefined
What allows any number of square brackets to surround the key and still successfully find the key in the object? Is there specific behavior when array.length === 1? And if so, where can I find documentation or clarity on that?
When using the object[key] bracket notation to access properties, the key is converted to a string.* The string representation of an array is the string representations of its elements joined with ,. For a one-element array, that's the same as the string representation of its only element.
const foo = {'a,b': 2};
console.log(foo[['a', 'b']]); // 2;
* Or a symbol.
When you access a property using square brackets, the key is always converted to string. And if you convert an array to string, the result is the same as calling the join() method on the array. Therefore, converting to string an array, which contains only one element, which is a string results in that element itself. However, when array contains two string elements (like ['one', 'two']), converting it to string results in 'one,two', and the data variable doesn't contain that key.

Java Script for of [duplicate]

This question already has answers here:
Why for .. in gets all the properties, but for .. of doesn't get all the values?
(2 answers)
Closed 6 years ago.
Can you explain me, please, why first console.log shows me array with both:
array.foo and item, but when I use for of loop it does not show array.foo?
let array = [3,5,8, item = 'good'];
array.foo = 'hello';
console.log(array);
for (var i of array) {
console.log( i);
}
The for-of runtime semantics tell us that we will iterate over ForIn/OfHeadEvaluation( « », AssignmentExpression, iterate). Which in turn returns us the GetIterator(exprValue) (see 8.b). GetIterator returns an iterator from the ##iterator slot (or Symbol.iterator). Which for an array returns the Array.prototype.values which uses CreateArrayIterator whose semantics are defined here.
And as you can see at %ArrayIteratorPrototype%.next( ) it iterates through the indexes from 0 through length - 1 and says nothing about other properties.
So, to summarise, the for-of does not iterate through non-index properties because the array iterator does not do so.

Categories

Resources