Chain function on array.flat() not working - javascript

Why chaining function on array.flat not working as expected
const input = [[[{"type":"banana"},{"type":"orange"}]]];
console.log(input.flat(2).push({"type":"grapes"}));
What I expect is, it should remove the 2 array wrapper and push a new item to input
But I get only the length why is that ?

Array#push returns the new length of the array.
You could concat the array (Array#concat) with a new element and get the new array.
console.log(input.flat(2).concat({ type: "grapes" }));

Array.push mutates the array itself and returns only the length of the array. You can log the array in the next line after the push statement.

The push method returns the new length of the array and mutates it.
Try instead:
const input = [[[{"type":"banana"},{"type":"orange"}]]];
const flattened = input.flat(2)
flattened.push({"type":"grapes"});
console.log(flattened)
/*
[
{type:"banana"},
{type:"orange"},
{type:"grapes"}
]
*/

You can also other than Array.concat also spread into a new array to achieve the same result:
const input = [[[{"type":"banana"},{"type":"orange"}]]];
console.log([...input.flat(2), {"type":"grapes"}]);
The issue in your code however is that Array.flat returns a whole new array for you to work with and Array.push simply returns the new length of the array (so you need to keep a reference to the array). So with some refactoring:
const input = [[[{"type":"banana"},{"type":"orange"}]]];
let newArr = input.flat(2) // <-- this would return a new array
newArr.push({"type":"grapes"}) // We do not care what push returns since we have a reference to the array
console.log(newArr)
You get the expected result
Also note of caution with Array.flatMap and Array.flat ... both do not have support in IE and you would need a polyfill

Related

What is the different vs array.push() and array = [...array, newItem]?

I have seen some YouTubers not use array.push() to add items to an array but rather do something like:
let item = 3
let array = [1, 2];
array = [...array, item]; // Why not use array.push()?
Is there any difference between the two methods and which one should i use?
Push: Use push when you want to add data in the existing array and don't want to cra
When you use the push method, you are adding the element to the existing one i.e not creating a new array.
The push() method adds one or more elements to the end of an array and
returns the new length of the array. - MDN
const arr = [1, 2, 3, 4, 5];
const returnValue = arr.push(6);
console.log(arr);
console.log(returnValue)
Spread Syntax: Use spread syntax if you want to add elements in new array(it can be from spread or can add more new elements also) but will create a new array []
This is called spread syntax
Spread syntax (...) allows an iterable such as an array expression or
string to be expanded in places where zero or more arguments (for
function calls) or elements (for array literals) are expected, or an
object expression to be expanded in places where zero or more
key-value pairs (for object literals) are expected.
let array = [1, 2];
let item = 3
result = [...array, item];
console.log(result === array);
In the above snippet you are creating a new array and assigning values 1, 2 then you are using spread syntax to spread it into a new array. You can also add new elements also like item whose value is 3.
array.push manipulates the existing array. The latter makes a new copy with the new value.
Array push is used to push items kn exisiting array but if we want a copy of an element of an array as a new array variable- you can use […array] operator.

Pushing simple value into an array on the fly

I want to be able to create an array with only one value inside of it on the fly without using a variable. This works with a variable:
var arr = [];
arr.push('test');
console.log(arr); // correctly logs ["test"]
But this does not:
console.log([].push('test')); // logs 1
Why does this log 1 instead of ["test"]? Is this coerced into a boolean?
Array.prototype.push returns the new length of the array, not the pushed item nor the array it-self.
"I want to be able to create an array with only one value inside of it
on the fly without using a variable"
const arr = ['test'];
console.log(['test']);
Array.prototype.push()
The push() method adds one or more elements to the end of an array and returns the new length of the array.
In the first example you are first pushing the element in the array then log the array. But in the second example you are logging the returned result of push().

JSON.parse returns an array, but cannot be used as an array

Consider the following situation:
const JSONString = `["a", "b"]`;
console.log(JSON.parse(JSONString).push("c")); //returns 3 (length)
Why does JSON.parse return the array and allows Array methods on it, but when you actually try to push something in the array it returns the length?
If we do the following it will work:
const JSONString = `["a", "b"]`;
console.log(JSON.parse(JSONString).concat("c"));
Here above is the original question and answered correctly below by Quentin.
Performance question:
Would would be preferable in the situation above: concat or push, where concat is only one line but returns a new array. push needs more lines of code, but keeps the original array?
Why does JSON.parse return the array
Because it is an array
allows Array methods on it
Because it is an array
when you actually try to push something in the array it returns the length?
Because the return value of the push function is the length of the array
To quote MDN:
The push() method adds one or more elements to the end of an array and returns the new length of the array.
JSON.parse is irrelevant to this:
const array = ["a", "b"];
const return_value = array.push("c");
console.log({ array, return_value });
Would would be preferable in the situation above: concat or push, where concat is only one line but returns a new array. push needs more lines of code, but keeps the original array?
If you need the original array then the answer is obvious.
If you don't, then it is a matter of opinion.

Array.push() with Objects

Is there any reason why I canot .push() objects into an Array? Simplified example below.
let myArray = [{x:1},{x:2}];
let myObj = {x:1};
let x = myArray.push(myObj);
console.log(x)
// I'am expecting [{x:1},{x:2},{x:1}] but I get 3
The return value of push is the length of the modified array. It isn't another reference to the same array, nor is it a new array.
If you want to log the array, then console.log(myArray) instead of x.
Simple, push just returns the length of the new array and the array was modified in place. Try:
console.log(myArray)
myArray.push(myObj) returns a number of objects it has. you are displaying the array length. If we print myArray you could see the array of Object.
You should console.log(myArray); The way you do returns the new length of the array, which you assign another reference
DEMO
let myArray = [{x:1},{x:2}];
let myObj = {x:1};
console.log(myArray);
myArray.push(myObj);
console.log(myArray);
Array.push() function is working properly, and it returns the new length of the array
The push() method adds one or more elements to the end of an array and returns the new length of the array.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push?v=a

What does empty array.slice(0).push(anything) mean?

I want to clone a new array from an existing one and push in an element.
Unfortunately, the existing array is an empty one, so it's like:
[].slice().push(65)
the output of above expression is 1.
Why is it 1?
Array#push() returns the length of the resultant array. Since you're pushing a single value onto an empty array, the length of the result will indeed be 1.
If you want to see the updated array as output, you'll need to save a reference to it since push() does not return a reference:
var arr = [].slice();
arr.push(65);
console.log(arr); // [ 65 ]
Changing my comment to an answer:
MDN push(): The push() method adds one or more elements to the end of an array and returns the new length of the array.
You need to do it in two steps, not one with that pattern.
var temp = [].slice();
temp.push(65);
console.log(temp);
If you want to do it in one line, look into concat()
var a = [1,2,3];
var b = [].concat(a,64);
console.log(b);

Categories

Resources