Merge two arrays by value - javascript

I have a specific cuestion about merge arrays:
I'm using google charts and I need to do something like this
Combo Chart
To do something like that I need to fill this matrix
I did fine with axis x and axis y:
$scope.data= [];
$scope.data[0]= ['Months'];
angular.forEach($scope.consultors, function(consultor) {
$scope.data[0].push(consultor.no_user);
})
angular.forEach(months, function(month) {
$scope.data.push([month])
})
but, my problem is when i try to put $scope.relatorias, inside of $scope.data.
This is $scope.relatorias, this variable has the data of every consultor group by month, like this:
If you open each array look like this
I just need push ganancias_netas, but my problem is when there is an empty month, for example anapaula has data in every month but renato hasn't.
I have try to user for or for each but is doesn't work, I'm not an expert in matrix and this is my first time working on it.
fiddle: http://fiddle.jshell.net/rfcabal/5ftw7c8d/
/// UPDATE ///
I added this code that first fill with 0 $scope.data and then search for the values in relatorios and shoudl fill $scope.data, but for some reason jus fill with the last found value.
for (var i = 1; i < $scope.data.length; i++) {
for (var a = 1; a < $scope.data[0].length; a++) {
$scope.data[i][a] = 0;
for (var b = 0; b < $scope.relatorios[a-1].length; b++) {
console.log(a-1+' '+b+' '+3);
console.log($scope.relatorios[a-1][b]['ganancias_netas'])
$scope.data[i][a] = $scope.relatorios[a-1][b]['ganancias_netas'];
}
}
}
Thanks for your help

I just solved with 2 for
First i fill every data space with 0
for (var i = 1; i < $scope.data.length; i++) {
for (var a = 1; a < $scope.data[0].length; a++) {
$scope.data[i][a] = 0;
}
}
The i jus remplace where fecha_emision equal to position 1 of every array.
for (var a = 0; a < $scope.relatorios.length; a++) {
for (var b = 0; b < $scope.relatorios[a].length; b++) {
for (var i = 1; i < $scope.data.length; i++) {
var index = $scope.data[i].indexOf($scope.relatorios[a][b]['fecha_emision']);
if(index >= 0) {
$scope.data[i][a+1] = parseFloat($scope.relatorios[a][b]['ganancias_netas']);
}
}
}
}

Related

Detecting object collision with spatial partitioning in JavaScript

I'm trying to create a system of many objects that preform an action when they collide with each other, I'm using the P5.min.js library.
I've set up an array for the grid and an array for the objects, but I can't figure out the right way to go through each grid cell and check only the objects inside that cell before moving on to the next cell.
Here's what I've got so far
let molecules = [];
const numOfMolecules = 100;
let collisions = 0;
let check = 0;
let maxR = 10; //max molecule radius
let minR = 2; //min molecule radius
let numOfCol = 5;
let numOfRow = 5;
let CellW = 600/numOfCol; //gridWidth
let CellH = 600/numOfRow; //gridHeight
let remain = numOfMolecules;
let gridArray = [];
function setup() {
createCanvas(600, 600);
background(127);
for (let i = 0; i < numOfMolecules; i++) {
molecules.push(new Molecule());
}
}
function draw() {
background(127);
molecules.forEach(molecule => {
molecule.render();
molecule.checkEdges();
molecule.step();
});
drawGrid();
splitIntoGrid();
collision();
displayFR();
}
function drawGrid() {
for (i = 0; i < numOfRow+1; i++){
for (j = 0; j < numOfCol+1; j++){
noFill();
stroke(0);
rect(CellW*(j-1), CellH*(i-1), CellW, CellH);
}
}
}
function splitIntoGrid(){
for (let i = 0; i < numOfRow; i++){
for (let j = 0; j < numOfCol; j++){
tempArray = [];
molecules.forEach(molecule => {
if (molecule.position.x > (CellW*j) &&
molecule.position.x < (CellW*(j+1)) &&
molecule.position.y > (CellH*i) &&
molecule.position.y < (CellH*(i+1))) {
tempArray.push(molecule.id);
}
});
}
}
}
How I'm checking collision between all objects:
function collision() {
for (let i=0; i < molecules.length; i++){
for (let j=0; j < molecules.length; j++){
let diff = p5.Vector.sub(molecules[j].position, molecules[i].position);
check++;
if (i != j && diff.mag() <= molecules[j].radius + molecules[i].radius){
collisions++;
molecules[j].changeColor();
}
}
}
}
As far as I can see, I need to put these for loops inside another one going through each cell in the grid, but I don't know how to limit the search to which ever tempArray(s) the object is in
If this makes any sense, this is what I'm trying to do
function collision() {
for (let k = 0; k < gridArray.length; k++){
for (let i=0; i < gridArray.tempArray.length; i++){
for (let j=0; j < gridArray.tempArray.length; j++){
let diff = p5.Vector.sub(gridArray.tempArray[j].position, gridArray.tempArray.position);
check++;
if (i != j && diff.mag() <= gridArray.tempArray[j].radius + gridArray.tempArray[i].radius){
collisions++;
gridArray.tempArray[j].changeColor();
gridArray.tempArray[i].changeColor();
}
}
}
}
}
The grid cell is represented by an array of array gridArray. You need to have a collection of molecules for each grid cell. My recommendation would be to use Sets instead of an Array since the order is irrelevant. The idea is to be able to access the set of molecules on a given grid cell (i,j) with the syntax:
gridArray[i][j]
The following code will create an array of numOfRow arrays:
const numOfRow = 5;
const gridArray = (new Array(numOfRow)).fill([]);
gridArray with look like this:
[ [], [], [], [], [] ]
Inside splitIntoGrid you are checking which molecules are in which grid cells. This is good. However, for each grid cell, you are overwriting the global variable tempArray. Therefore, at the end of the function's execution, tempArray will only hold the molecules of the last grid cell, which isn't what you want. For a given grid cell, we will add the right molecules to a Set associated with this grid cell.
The Set data structure has an #add method which appends a new element to the set:
function splitIntoGrid() {
for (let i = 0; i < numOfRow; i++) {
for (let j = 0; j < numOfCol; j++) {
gridArray[i][j] = new Set();
molecules.forEach(molecule => {
if (molecule.position.x > (CellW*j)
&& molecule.position.x < (CellW*(j+1))
&& molecule.position.y > (CellH*i)
&& molecule.position.y < (CellH*(i+1))) {
gridArray[i][j].add(molecule);
}
});
}
}
}
Now you're ready to check for collisions on each grid cells. We will have a total of four loops inside one another. Two to navigate through the grid and two to compare the molecules that are contained inside each grid cell:
function collision() {
for (let i = 0; i < numOfRow; i++) {
for (let j = 0; j < numOfCol; j++) {
gridArray[i][j].forEach(moleculeA => {
gridArray[i][j].forEach(moleculeB => {
const diff = p5.Vector.sub(moleculeA.position, moleculeB.position);
if (moleculeA != moleculeB && diff.mag() <= moleculeA.radius + moleculeB.radius) {
collisions++;
moleculeA.changeColor();
moleculeB.changeColor();
}
});
});
}
}
}
In the above code, #forEach comes in handy.

Why is this 2d array pushing values when it shouldn't?

EDITED: Thanks for pointing out my oblivious mistake with tempRndNumber being reset in the inner loop.
I'm still seeing "," characters show up in the array though.
I want to create a 2d array that only gets populated when a random number meets a particular criteria (rnd >= 7). But the following code populates the 2d array with a combination of "," and the numbers that meets the criteria.
var tempAllRndNumbers = [];
for (var i = 0; i < 10; i++) {
for (var j = 0; j < 10; j++) {
var tempRndNumber = [];
var rndNumber = Math.floor(Math.random() * 10);
if (rndNumber >= 7) {
tempRndNumber.push(rndNumber);
}
}
tempAllRndNumbers.push(tempRndNumber);
}
tempAllRndNumbers should only be populated with numbers 7 and above, right? But instead, I'm getting a 2D array full of "," and numbers 7 and above.
Since you reset tempRndNumber to an empty array on each iteration of the j loop, it will only contain a number if the last iteration was >= 7. Move the initialization outside of the innermost loop:
var tempAllRndNumbers = [];
for (var i = 0; i < 10; i++) {
var tempRndNumber = [];
for (var j = 0; j < 10; {
var rndNumber = Math.floor(Math.random() * 10);
if (rndNumber >= 7) {
tempRndNumber.push(rndNumber);
}
}
tempAllRndNumbers.push(tempRndNumber);
}
You have no check to see if the tempRndNumber array has any values, so you are pushing an empty array into the array tempAllRndNumbers. That's why you have the ','s, you have indexes with no values.
I don't think you want to reset tempRndNumber in each iteration of your inner loop like you are. Try this:
var tempAllRndNumbers = [];
for (var i = 0; i < 10; i++) {
var tempRndNumber = [];
for (var j = 0; j < 10; j++) {
var rndNumber = Math.floor(Math.random() * 10);
if (rndNumber >= 7) {
tempRndNumber.push(rndNumber);
}
}
tempAllRndNumbers.push(tempRndNumber);
}
UPDATE:
You have to loop back through both arrays to get the proper output, see here:
http://jsfiddle.net/jessikwa/1fbq0woo/

Using Google Script to get an array from a list of cells in google sheet

How do I create an array of values that are in a set of cells in Google sheets?
The array should be the same rows and columns as the cells and it should have the same values as the sheet has in each location.
Also, I want to be able to pass the range of the array in as a parameter so that I can use the function for different ranges.
edit 2:
New code, nearly working, I just need to have it receive the ranges from user input on the google sheet itself. This is what I am trying to get work, but the beginning is struggling to work, I can't pass in a choice of ranges and have the cell update and have the function run.
Also, I am having a problem with getting a reference error almost every time even when I try to preset the ranges within the function without any parameters
function sortingtest(pWO, pInfo, pSearch) {
var WO = SpreadsheetApp.getActiveSpreadsheet().getRange(pWO).getValues();
var Info = SpreadsheetApp.getActiveSpreadsheet().getRange(pInfo).getValues();
var Search = SpreadsheetApp.getActiveSpreadsheet().getRange(pSearch).getValues();
//[row][column]
var FinalArray1 = [];
var FinalArray2 = [];
var FinalArray3 = [];
var LastArray = [];
var a = 0;
var b = 0;
var c = 0;
var d = 0;
for (var row = 0; row < WO.length; row ++) {
var counter = row - 1;
while (WO[row] == "") {
WO[row] = WO[counter];
counter--;
}
}
for (var col = 0; col < Info[0].length; col++) {
for (var row = 0; row < Info.length; row++) {
if (Info[row][col] == Search[col]) {
if (col == 0) {
FinalArray1[a] = WO[row];
a++;
}
else if (col == 1) {
FinalArray2[b] = WO[row];
b++;
}
else if (col == 2) {
FinalArray3[c] = WO[row];
c++;
}
}
}
}
for (var i = 0; i < FinalArray1.length; i++) {
for (var j = 0; j < FinalArray2.length; j++) {
for (var k = 0; k < FinalArray3.length; k++) {
if (FinalArray3[k] == FinalArray2[j] && FinalArray2[j] == FinalArray1[i]) {
LastArray[d] = FinalArray1[i];
d++;
}
}
}
}
return LastArray;
}
If you call your function from within the spreadsheet as you indicate it in your comment (=sortingtest(sheet1!A1:C12,sheet3!D1:E12,sheet2!F1:G4)), you do not need to call any of the SpreadsheetApp functions to get arrays: pWO, pInfo and pSearch will already be 2 dimensional arrays.
Quoting the Google custom function article:
If you call your function with a reference to a range of cells as an argument (like =DOUBLE(A1:B10)), the argument will be a two-dimensional array of the cells' values. For example, in the screenshot below, the arguments in =DOUBLE(A1:B2) are interpreted by Apps Script as double([[1,3],[2,4]]).

Searching a 2D Javascript Array For Value Index

I am trying to write a jQuery that will find the index of a specific value within a 7x7 2D array.
So if the value I am looking for is 0 then I need the function to search the 2D array and once it finds 0 it stores the index of the two indexes.
This is what I have so far, but it returns "0 0" (the initial values set to the variable.
Here is a jsFiddle and the function I have so far:
http://jsfiddle.net/31pj8ydz/1/
$(document).ready( function() {
var items = [[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,0,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7]];
var row = 0;
var line = 0;
for (i = 0; i < 7; ++i) {
for (j = 0; i < 7; ++i) {
if (items[i, j] == '0,') {
row = i;
line = j;
}
}
}
$('.text').text(row + ' ' + line);
});
HTML:
<p class="text"></p>
Your if statement is comparing
if (items[i, j] == '0,')
Accessing is wrong, you should use [i][j].
And your array has values:
[1,2,3,4,5,6,7]
....
Your value '0,' is a string, which will not match numeric values inside the array, meaning that your row and line won't change.
First, you are accessing your array wrong. To access a 2D array, you use the format items[i][j].
Second, your array doesn't contain the value '0'. It doesn't contain any strings. So the row and line variables are never changed.
You should change your if statement to look like this:
if(items[i][j] == 0) {
Notice it is searching for the number 0, not the string '0'.
You access your array with the wrong way. Please just try this one:
items[i][j]
When we have a multidimensional array we access the an element of the array, using array[firstDimensionIndex][secondDimensionIndex]...[nthDimensionIndex].
That being said, you should change the condition in your if statement:
if( items[i][j] === 0 )
Please notice that I have removed the , you had after 0. It isn't needed. Also I have removed the ''. We don't need them also.
There are following problems in the code
1) items[i,j] should be items[i][j].
2) You are comparing it with '0,' it should be 0 or '0', if you are not concerned about type.
3) In your inner for loop you should be incrementing j and testing j as exit condition.
Change your for loop like bellow and it will work
for (i = 0; i < 7; i++) {
for (j = 0; j < 7; j++) {
if (items[i][j] == '0') {
row = i;
line = j;
}
}
}
DEMO
Note:-
1) Better to use === at the place of ==, it checks for type also. As you see with 0=='0' gives true.
2) Better to say i < items.length and j<items[i].length instead of hard-coding it as 7.
var foo;
items.forEach(function(arr, i) {
arr.forEach(function(val, j) {
if (!val) { //0 coerces to false
foo = [i, j];
}
}
}
Here foo will be the last instance of 0 in the 2D array.
You are doing loop wrong
On place of
for (i = 0; i < 7; ++i) {
for (j = 0; i < 7; ++i) {
if (items[i, j] == '0,') {
row = i;
line = j;
}
}
}
use this
for (i = 0; i < 7; i++) {
for (j = 0; j < 7; j++) {
if (items[i][j] == 0) {
row = i;
line = j;
}
}
}
Here is the demo
looks like you are still learning how to program. But here is an algorithm I've made. Analyze it and compare to your code ;)
var itens = [[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,0,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7]];
var row = null;
var collumn = null;
for (var i = 0; i < itens.length; i++) {
for (var j = 0; j < itens[i].length; j++) {
if (itens[i][j] == 0) {
row = i;
collumn = j;
}
}
}
console.log(row, collumn);

How to dynamically update 3 dimensional Array values in Javascript

I have a 3d array-DataSeriesToPlot in Javascript, what I want to do is all first half rows' elements value plus a value- scale, all remaining half rows'elements value minus the value-scale. The code is like the below showed,
for ( var i = 0; i < DataSeriesToPlot.length; i++) {
for ( var j = 0; j < DataSeriesToPlot[i].length; j++) {
if ((i >= 0) && (i < (DataSeriesToPlot.length / 2))) {
DataSeriesToPlot[i][j][1] = (parseFloat(DataSeriesToPlot[i][j][1]) + parseFloat(scale))
.toFixed(2);
} else {
DataSeriesToPlot[i][j][1] = (parseFloat(DataSeriesToPlot[i][j][1]) - parseFloat(scale))
.toFixed(2);
}
for ( var j = 0; j < DataSeriesToPlot.length; j++) {
console.log("aaaaa"+DataSeriesToPlot[j]);
}
But this ways seems incorrect, because the console output the original value of this 3d array, all values haven't been changed. Could you please help me figure out where the error is? Thanks!

Categories