Excel Office Script - error trying to push a 2D Array - javascript

I'm having an issue of understanding and I'll try to be basic with my problem because it involves lots of data. Here is a simple mockup.
From myArray below, I'm trying to create a new 2D array (arrayFinal) in the form of [[element],[element],[element]], to be able to use a setValues() with Excel Office Script. In this example, each element should have more than 2 elements.
But I'm truly not going anywhere with my way.
I only get a return like, with too many [[[]]] (one too many), and only the last element repeating itself.
[[[1,5,7]],[[1,5,7]],[[1,5,7]],[[1,5,7]],[[1,5,7]],[[1,5,7]]]
Could you have a look and tell me what's the problem ?
let myArray: number[][] = [[1, 2, 3], [2, 4], [5, 6, 7],[1],[2,3],[1,5,7]];
let testArray: (string | boolean | number)[][] = [];
let arrayFinal: (string | boolean | number)[][] = [];
myArray.map(x => {
testArray.length = 0;
if (x.length > 2) {
testArray.push(x);
}
arrayFinal.push(testArray);
})
console.log(JSON.stringify(arrayFinal))
Thank you !

If I understand it correctly, you are trying to filter the original 2D array to only contain sub-arrays with more than 2 elements, right?
Wondering if you would want to try something like this:
let myArray: number[][] = [[1, 2, 3], [2, 4], [5, 6, 7],[1],[2,3],[1,5,7]];
let arrayFinal = myArray.filter(arr => arr.length > 2);
console.log(JSON.stringify(arrayFinal))
The output should be:
[[1,2,3],[5,6,7],[1,5,7]]

Related

How to convert an array to multiple array

I have an array abc = [1, 2, 3].
How can i convert it to multiple arrays: [1, 2] , [1, 3], [2, 3]
Note: If abc have n items, we will convert to n*(n-1) arrays
you could do something like this:
const combinations = arr =>
arr.flatMap((elX, indexX) =>
arr
.filter((_, indexY) => indexY == indexX)
.map(elY => [elX, elY])
)
the result will be n*(n-1) so for [1,2,3] = [[1,2],[1,3],[2,1],[2,3],[3,1],[3,2]]
Looks like you want to list all kind of combination to be made from original array
you can run code below in console to check if it fits your needs
Note that in code below, i use filter to avoid same value in the same array group
Sorry for my bad english
let arr = [1, 2, 3];
arr = arr.map((currentValue, index, arr)=>{
return arr.filter((val2, idx2) => val2 !== currentValue);
});
document.write(JSON.stringify(arr,null,4));
Edit: i know the question wants 6 arrays, this code above is following the example he gave... This is alternative answer if what he really meant was to find every single unique combination (without mirror effect)

How would one add items to the beginning of an array with Lodash?

I've been searching for a while to add items to the beginning of an array with lodash. Unfortunately I can't seem to find anything other than lodash concat (to the end of the array). The docs don't seem to say anything about it either.
I got the following code:
const [collection, setCollection] = useState({
foo: [1, 2, 3]
});
const addToCollection = (key, items) => {
setCollection(prevCollection => ({
...prevCollection,
[key]: _.concat(prevCollection[key] || [], items)
}));
};
But this concats all the items to the end. I don't want to sort them every time because that uses unnessecary processing power, I would much rather just add them to the beginning because the API always pushes the items already sorted
How would I accomplish this:
addToCollection('foo', [4, 5, 6]);
console.log(collection['foo']) // [4, 5, 6, 1, 2, 3];
Instead of what is happening now:
addToCollection('foo', [4, 5, 6]);
console.log(collection['foo']) // [1, 2, 3, 4, 5, 6];
Try swapping the arguments:
_.concat(items, prevCollection[key] || [])
Or vanilla JS is pretty easy too:
Collection.unshift('addMe', var, 'otherString' )
https://www.w3schools.com/jsref/jsref_unshift.asp#:~:text=The%20unshift()%20method%20adds,use%20the%20push()%20method.
I know you asked for lodash but I figured this is a good thing to be aware of too :)
EDIT:
To clarify, this works the same whether you're pushing defined vars, string, arrays, objects or whatever:
let yourArray = [1,2,3];
let pushArray = [1,2,3,4];
let anotherArray = [7,8,9];
yourArray.unshift(pushArray, anotherArray);
will push "pushArray" and "anotherArray" to the begining of "yourArray" so it's values will look like this:
[[1,2,3,4], [7,8,9], 1,2,3]
Happy Coding!

JS - For Loops Pushing Array

I have an initial array,
I've been trying to change values (orders) by using pop, splice methods inside a for loop and finally I push this array to the container array.
However every time initial array is values are pushed. When I wrote console.log(initial) before push method, I can see initial array has been changed but it is not pushed to the container.
I also tried to slow down the process by using settimeout for push method but this didnt work. It is not slowing down. I guess this code is invoked immediately
I would like to learn what is going on here ? Why I have this kind of problem and what is the solution to get rid of that.
function trial(){
let schedulePattern = [];
let initial = [1,3,4,2];
for(let i = 0; i < 3; i++){
let temp = initial.pop();
initial.splice(1,0,temp);
console.log(initial);
schedulePattern.push(initial);
}
return schedulePattern;
}
**Console.log**
(4) [1, 2, 3, 4]
(4) [1, 4, 2, 3]
(4) [1, 3, 4, 2]
(3) [Array(4), Array(4), Array(4)]
0 : (4) [1, 3, 4, 2]
1 : (4) [1, 3, 4, 2]
2 : (4) [1, 3, 4, 2]
length : 3
When you push initial into schedulePattern, it's going to be a bunch of references to the same Array object. You can push a copy of the array instead if you want to preserve its current contents:
schedulePattern.push(initial.slice(0));
Good answer on reference types versus value types here: https://stackoverflow.com/a/13266769/119549
When you push the array to schedulepattern, you are passing a reference to it.
you have to "clone" the array.
use the slice function.
function trial(){
let schedulePattern = [];
let initial = [1,3,4,2];
for(let i = 0; i < 3; i++){
let temp = initial.pop();
initial.splice(1,0,temp);
console.log(initial);
schedulePattern.push(initial.slice());
}
return schedulePattern;
}
​
You have to know that arrays are mutable objects. What does it mean? It means what is happening to you, you are copying the reference of the object and modifying it.
const array = [1,2,3]
const copy = array;
copy.push(4);
console.log(array); // [1, 2, 3, 4]
console.log(copy); // [1, 2, 3, 4]
There are a lot of methods in Javascript which provide you the way you are looking for. In other words, create a new array copy to work properly without modify the root.
const array = [1,2,3]
const copy = Array.from(array);
copy.push(4);
console.log(array); // [1, 2, 3]
console.log(copy); // [1, 2, 3, 4]
I encourage you to take a look at Array methods to increase your knowledge to take the best decision about using the different options you have.

Find largest adjacent product in array (JavaScript)

I'm trying to understand the following solution for finding the largest adjacent product in any given array.
Example:
For inputArray = [3, 6, -2, -5, 7, 3], the output should be
adjacentElementsProduct(inputArray) = 21.
7 and 3 produce the largest product.
Possible solution in JS:
function adjacentElementsProduct(arr) {
return Math.max(...arr.slice(1).map((x,i)=>[x*arr[i]]))
}
I am having a hard time understanding two things:
What do the three dots exactly do and how does this get passed into the function? Is there any way to write this in a more understandable way? I know that is the "spread syntax" feature in ES6, but still don't understand completely.
Why do we insert "1" as argument to slice? My first though was to input "0", because we want to start at the start, then loop through everything, and see which adjacent product is the largest.
I'd appreciate any advice, links and explanations.
Thanks.
Cheers!
1. What do the three dots exactly do and how does this get passed into the function? Is there any way to write this in a more understandable way? I know that is some kind of "spread" feature in ES6, but still don't understand completely.
The Math#max needs a list of numbers as parameters, and map produces an array. The spread syntax is used to convert an array to be expanded to a list of parameters.
const arr = [1, 2, 3];
console.log('max on array', Math.max(arr));
console.log('max on list of parameters', Math.max(...arr));
In this case you can use Function#apply to convert the array to a list of parameters. I find it less readable, however.
const arr = [1, 2, 3];
console.log(Math.max.apply(Math, arr));
2. Why do we insert "1" as argument to slice? My first though was to input "0", because we want to start at the start, then loop through everything, and see which adjacent product is the largest.
Lets break down the iteration order of the 2 arrays.
[3, 6, -2, -5, 7, 3] // inputArray
[6, -2, -5, 7, 3] // inputArray.slice(1)
Now on each iteration of inputArray.slice(1):
x: 6, i = 0, arr[0] = 3
x: -2, i = 1, arr[1] = 6
x: -5, i = 2, arr[2] = -2
Since the inputArray.slice(1) array starts from the 2nd element of the inputArray, the index (i) points to the 1st element of the inputArray. And the result is an array of products of 2 adjacent numbers.
var biggestProduct = inputArray[0] * inputArray[1];
for (i=0; i<inputArray.length-1 ; ++i)
{
console.log(biggestProduct)
if ((inputArray[i] * inputArray[i+1] ) > biggestProduct)
{
biggestProduct = inputArray[i] * inputArray[i+1]
}
}
return biggestProduct;
Note: I've declared a variable that consists of 2 input arrays with index number then starts a for loop that indicates input array with his index number, so by that he will go throw all the index number of the array (one of them raised by one so that they won't be at the same value). and at the end of the code, you have the if statement.
You may simply do as follows;
function getNeigboringMaxProduct([x,...xs], r = -Infinity){
var p = x * xs[0];
return xs.length ? getNeigboringMaxProduct(xs, p > r ? p : r)
: r;
}
var arr = [3, 6, -2, -5, 7, 3],
res = getNeigboringMaxProduct(arr);
console.log(res);

Choose if array element repeats itself twice -- Javascript [duplicate]

This question already has answers here:
Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array
(97 answers)
Closed 6 years ago.
There is a javascript array
var arr = [0, 1, 2, 2, 3, 3, 5];
I want to choose elements that repeats twice. In this case its 2 and 3. and i want attach them into a variable.
var a = 2, b = 3;
As far as i know there is no built-in function to do that job. How can i do that. Thanks.
You can use filter to get the values that occur twice.
var arr = [0, 1, 2, 2, 3, 3, 5];
var dups = arr.filter ( (v,i,a) => a.indexOf(v) < i );
console.log(dups);
In comments you stated you would only have doubles, but no values that occur more than twice. Note that the above would return a value more than once, if the latter would be the case.
This returns the values in an array, which is how you should work. To put them in separate values can be done as follows:
var [a, b, ...others] = dups;
...but you would have to know how many variables to reserve for that, and it does not make your further program any easier. JavaScript has many nice functions (methods) for arrays, so you should in fact leave them in an array.
There is no built in function to do that indeed.
You will have to loop thought the array and keeping track of the number of occurrences of the elements, while building a response array.
You could filter a sorted array.
var arr = [0, 1, 2, 2, 3, 3, 5],
repeats = arr.filter(function (a, i, aa) {
return aa[i - 1] === a;
});
console.log(repeats);
Most simple way to do this is the following:
var dups = [];
var arr = [0, 1, 2, 2, 3, 3, 5];
arr.forEach(function (v, i, a){
delete arr[i];
if (arr.indexOf(v) !== -1){
dups.push(v);
}
});
console.log(dups);
It's destructive however.

Categories

Resources