Adding to a 2 dimensional array with unshift - javascript

I have a 2 dimensional array:
var sH = [['two'],['three']]
and I want to add 'one' to the start/top so my array ends up as
[['one'],['two'],['three']]
Using unshift like so
sH[0].unshift('one');
produces an array where 'one is inserted but 'two' is in the second column rather than the first (ie 1 rather than 1[0])
I've looked and searched and experimented but I cannot see how to do this easily.

The statement sH[0].unshift will affect the bound object - which is an array ( the first of the existing two (two, three); which is two)
In other words, using that method you adds the "one" to the first existing child array which is "two", producing
[['one', 'two'], 'three']
To produce [['one'], ['two'], ['three']] you should use sH.unshift('one');

Perhaps I misunderstand, but don't you just want to do the following?
sH.unshift(['one'])

var sH = [['two'],['three']];
sH.unshift(['one']); // [["one"], ["two"], ["three"]]
sH.push(['four']); // [["one"], ["two"], ["three"], ["four"]]

You are doing it wrong with your sh index.
It should be sh.unshift(['one']);
This will insert an array containing "one" string.

Related

GoogleScript - convert arrays of different lengths into arrays of the same length

To be able to use setValues() instead of setValue on a high number of rows, I would like to know how can I convert all my arrays into arrays of the same length.
During a map function, I create one giant array that looks like this :
const myArray = [[Monday, Tuesday],[Monday,Tuesday,Wednesday],[Friday],[Monday,Friday],[Tuesday,Wednesday,Friday]] // And so on.
At the moment I use a setValue for each item of the array. The next step would be simply to use setValues(), and append an array but the problem is they are all of different lengths.
result.forEach(function(_,index){
currentSheet.getRange(1+index,5).setValue(result[index]);
});
That is going to do that for 600 lines and I will do it several times with other functions. I can live with it, but it seems like a waste. Is there a way to make the arrays homogenous (all arrays would be have a length of 3 elements, one or two being empty for example) an use one single setValues() instead ?
EDIT : the original map function to create the first array was requested. Here it is :
(Basically what it does is : it runs a map through a first array, look at the first element and go find in the source all the elements that have the same key and return the 9th and 10th elements of that array)
const result = UniquesDatas.map(uniqueRow =>
SourceDatas
.filter(row => row[0] === uniqueRow[0])
.map(row => [row[9]+" "+row[10]])
);
Thank you in advance,
Cedric
You can concat an array of empty elements of the remaining length.
const myArray = [['Monday', 'Tuesday'],['Monday','Tuesday','Wednesday'],['Friday'],['Monday','Friday'],['Tuesday','Wednesday','Friday']]
const res = myArray.map(x => x.concat(Array(3 - x.length)));
console.log(res);
As suggested by Kinglish, to get the length of the inner array with the most elements, use Math.max(...myArray.map(x=>x.length)), which will work for the more general case.

Concat 2 arrays but one of them contains subarray

I have 2 arrays. The first one is simple:
The second one contains sub-arrays:
and every element of the sub-arrays should be concated to the first one so they can form one array of same elements.
Here is sandbox:
https://codesandbox.io/s/smoosh-dust-kpg5l?file=/src/App.js
Arrays are data1 and data2. Final data is how it should look like. I tried several loops to form it but unsuccessfully.
Array#flatMap to the rescue:
const newArr = [...data1, ...data2.flatMap((el) => el)];

Javascript slice isn't giving me correct array length values

Why does it say length 1 instead of 4?
The following is what I'm trying to push and slice. I try and append items.image_urls and slice them into 5 each.
items.image_urls is my dictionary array.
var final_push = []
final_push.push(items.image_urls.splice(0,5))
console.log(final_push.length)## gives me 1...?
var index = 0
final_push.forEach(function(results){
index++ ##this gives me one. I would need 1,2,3,4,5,1,2,3,4,5. Somehting along that.
}
items.image_urls looks like this:
It's an iteration of arrays with image urls.
In your example items.image_urls.splice(0,5) returns an array of items removed from items.image_urls. When you call final_push.push(items.image_urls.splice(0,5));, this whole array is pushed as one item to the final_push array, so it now looks like [["url1", "url2", "url3", "url4", "url5"]] (2-dimensional array). You can access this whole array by calling final_push[some_index].
But what you want instead is to add every element of items.image_urls.splice(0,5) to the final_push. You can use a spread operator to achieve this:
final_push.push(...items.image_urls.splice(0,5));
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
This is exactly our case, because push() expects one or more arguments:
arr.push(element1[, ...[, elementN]])
And here is an example:
let items = {
image_urls: ["url1", "url2", "url3", "url4", "url5", "url6", "url7", "url8", "url9", "url10"]
};
let final_push = [];
final_push.push(...items.image_urls.splice(0,5));
console.log(final_push.length);
console.log(JSON.stringify(final_push));
console.log(JSON.stringify(items.image_urls));
Note: do not confuse Array.prototype.slice() with Array.prototype.splice() - the first one returns a shallow copy of a portion of an array into a new array object while the second changes the contents of an array by removing existing elements and/or adding new elements and returns an array containing the deleted elements.
That seems to be a nested array. So if you would access index 0, and then work on that array like below it will probably work:
console.log(final_push[0].length); //should print 4
The author is mixing up splice and slice. Probably a typo :)
You start at the beginning (0) and then delete 5 items.

Length of Array within Array

I have an object that I am pushing some ints, strings and arrays into an array. And I want to get the length of the array that is within said array.
This is my code
var all_categories = [];
all_categories.push({
title: theTitle,
id: theId,
sub: subcategories
});
Now I know that all_categories.length is the general way of getting the length and I believe that I can't run all_categories[0].sub[0].length will not work because the function does not exist.
Suggestions for a solution or work around?
In your statement all_categories[0].sub[0].length refers to the length of the first element of array named sub.
In order to see length of the array you should call:
all_categories[0].sub.length
Assuming that subcategories is the array you want the length of, take out the second [0]. You aren't trying to get the length of the first subcategory, you're trying to get the number of subcategories.

Understanding syntax of multi dimensional array in javascript

var test = [[
[1,2],[2,3],[3,4]
]];
alert(test[[0]].length);
This returns me 3, but I cannot understand what this actually mean. How come this result?
There are no multi-dimensional arrays in JavaScript. There are only nested arrays.
[ // test
[ // test[0]
[1,2], // test[0][0]
[2,3], // test[0][1]
[3,4] // test[0][2]
] //
] //
As you can see, test[0] has a length of three.
And test[[0]] is semantically incorrect(*) and collapses into test[0].
(*) The index operator ([]) expects a number, like in test[0]. If you don't pass a number to it (like in your test[[0]] case, where you pass the array [0]), a conversion to string will happen first. (This is because of the first note below.)
Arrays are converted to string by joining their members with a comma. [0].toString() is "0", and therefore test[[0]] is equivalent to test["0"], which is equivalent to test[0].
Notes:
The square brackets are used for property access as well, so that test["length"] is the same as test.length.
Consequently, something horrible like test[[0]][["length"]]) is equivalent to test[0].length and will give you 3.
Something like test[[0,0]] would be test["0,0"] - and since there is no property named "0,0" on that array, you will get undefined.
The array test[0] contains three items:
[1,2]
[2,3]
[3,4]
Hence, the result of the length is 3.
The length of array test is just one, since test contains only one array:
[1,2],[2,3],[3,4]
In fact this is not a multi-dimensional array, it's just an array containing arrays (called a jagged array, or nested array).
test[[0]] is same thing as test[0] and test[0] is an array
[1,2],[2,3],[3,4]
consisting of these elements.
if you want to access ,for instance, [2,3] you need to use this syntax:
test[0][1]
and test[0][1].length will give you 2.
This is a nested array. An array of arrays.
It will be more clear if you expand your example:
var test = [
[
[1,2],[2,3],[3,4]
],
[
[5,6],[7,8],[9,9],[6,7]
],
];
alert(test[[1]].length);
Now, your test is an array of two arrays. The first one of which is an array of 3 arrays. The second one is an array of 4 arrays.
Now, test.length is 2. test[0].length is 3. test[1].length is 4. [[n]] just collapses.
Demo: http://jsfiddle.net/abhitalks/6H7Lj/
If you want get the length of first arrays length then write
alert(test[0][0].length);

Categories

Resources