Add element to existing object with index and value - javascript

I would like to iterate through two arrays subtracting one arrays value from another and adding their specific difference values to an object. So for example I have:
var answer = [];
var boom = [1,2,3,4];
var other = [[1,2,3,4],
[2,3,4,5],
[6,7,8,9];
for(var i=0; i<other.length; i++) {
for(var e=0; e<4; e++){
answer[e] = boom[e] - other[i][e];
}
}
This give me an output of:
Object {0: -5, 1: -5, 2: -5, 3: -5}
Which is boom subtracted from the last array in other what I am looking for and I think I am very close to getting it is:
Object [{0: [ 0, 0, 0, 0]},
{1: [-1,-1,-1,-1]},
{2: [-5,-5,-5,-5]}];
You can see that it will add the results of each iteration of the second for loop to the object answer. How can I accomplish this?

for(var i=0; i<other.length; i++) {
answer[i] = [];
for(var e=0; e<4; e++){
answer[i][e] = boom[e] - other[i][e];
}
}

You need to initialize answer as an object not an as array, also you need to create a new answer array representing each set of values in other
var answer = {};
var boom = [1, 2, 3, 4];
var other = [
[1, 2, 3, 4],
[2, 3, 4, 5],
[6, 7, 8, 9]
];
for (var i = 0; i < other.length; i++) {
var temp = answer[i] = {};
for (var e = 0; e < 4; e++) {
temp[e] = boom[e] - other[i][e];
}
}
Demo: Fiddle

Related

How to generate an array filled with a few different values?

I want to generate the following array:
[3, 3, 3, 3, 4, 4, 5, 5, 5]
there are 3 different values that should repeat m, n, and k times. What is the easiest way to do that?
If I do Array(m + n + k).fill(...).fill(...).fill(...) the start and end points in later fill calls look not very straightforward.
Generate the arrays separately and then combine them into one final array
[
...Array(4).fill(3),
...Array(2).fill(4),
...Array(3).fill(5)
]
Create an array of values, and an array of repeat. Iterate the values with Array.map(), and return a new array filled with the values. Flatten by spreading into Array.concat():
const values = [3, 4, 5];
const repeat = [4, 2, 3];
const arr = [].concat(...values.map((v, i) => new Array(repeat[i]).fill(v)));
console.log(arr);
var arrValues = [3,4,5];
var arrRepeats = [4,2,3];
var arr = [];
for(var i =0; i< arrRepeats.length;i++){
arr.push(Array(arrRepeats[i]).fill(arrValues[i]));
}
console.log(arr)
Or
var arrValues = [3,5,4];
var arrRepeats = [4,2,3];
let arr = [];
for(var i =0; i< arrRepeats.length; i++){
for(var j=0; j<arrRepeats[i];j++){
arr.push(arrValues[i]);
}
}
console.log(arr)
Or you can do that if you wanna generate arrays and combine them
var arrValues = [3,5,4];
var arrRepeats = [4,2,3]; // m, n, k
var mainArr = [];
for(var i =0; i< arrRepeats.length; i++){
var arr = [];
for(var j =0; j < arrRepeats[i]; j++){
arr.push(j);
arr.fill(arrValues[i]);
}
mainArr.push(arr);
}
console.log(mainArr)

Array conversion?

I'm really new to javascript, and when trying to achieve the following I stumbled upon some problems. I tried searching the forum - and a problem like this is probably something that has been solved before, but I don't know what to search for. This is also the reason for the extremely creative title:/
Anyhow - this is my current code:
var arraylength = 4;
var originalarray = new Array(new Array);
var originalarray = {
[1, 1, 1, 1]
[2, 2, 2, 2]
[3, 3, 3, 3]
[4, 4, 4, 4]
}
convertarray(originalarray, arraylength);
function convertarray(originalarray, arraylength){
var converedtarray = new Array(new Array);
var temparray = new Array;
temparray.length = arraylength;
for (h = 0; h < arraylength; h++) {
var temparray = [];
var temparray = originalarray[h].split('');
for (i = 0; i < arraylength; i++) {
converedtarray[h][i] = temparray[i];
}
}
return convertedarray;
}
I am not entirely sure if the code speaks for itself, but this is pseudo for what I want to achieve;
originalarray = 1111, 2222, 3333, 4444
converedtarray = 1234, 1324, 1234, 1234
Can someone tell me what part I've missed or give me a hint of what I can do?
Because I'm getting "TypeError: undefined is not an object" at this part:
converedtarray[h][i] = temparray[i];
I am by no means a professional coder - I know the code isn't pretty, but this is more or less the result of trial-and error... More error than trial actually.
Thank you in advance for your answer!
A possible solution:
var arraylength = 4;
var originalarray = [
[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3],
[4, 4, 4, 4],
];
function convertarray(originalarray, arraylength) {
var result = [];
for (h = 0; h < arraylength; h++) {
result.push(
originalarray.map(function(subarray) {
return subarray[h];
})
);
}
return result;
}
console.log(
convertarray(originalarray, arraylength)
);
There are a few problems with your code. Firstly if you want a nXn array you have defined originalarray wrong. Second new Array(new Array) won't declare an array of array for you if that is what you were thinking. You will need two loops here as you have already figured out the first one for maintaining columns and the second one for rows.
var arraylength = 4;
var originalarray = new Array();
var originalarray = [
[1, 1, 1, 1],
[2, 2, 2, 2],
[3, 3, 3, 3],
[4, 4, 4, 4]
]
console.log(convertarray(originalarray, arraylength));
function convertarray(originalarray, arraylength){
var converedtarray = new Array();
for (h = 0; h < arraylength; h++) {
converedtarray[h] = [];
for (i = 0; i < arraylength; i++) {
converedtarray[h].push(originalarray[i][h]);
}
}
return converedtarray;
}

Create 2D array from 1D array using loop (JavaScript)

I have an array: [1, 2, 3, 4, 5, 6, 7, 8, 9]
I want to create a 2D array with three 1D arrays. Each NUM in the function variables is the length of each 1D array.
The result should be [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
But all I get is ,,3,,,6,,,9. What am I doing wrong?
function infiniteLoop(arr, num) {
var answer = [];
var count = 0;
for (let i = 0; i < num.length; i++) {
for (let j = 0; j < num[i]; j++, count++) {
answer[i] = [];
answer[i][j] = arr[count];
}
}
return answer;
}
document.write(infiniteLoop([1, 2, 3, 4, 5, 6, 7, 8, 9], [3, 3, 3]));
JavaScript doesn't have multidimensional arrays per se, what it has is arrays of arrays.
When you try to use answer[i][j] the answer[i] part of that is undefined because you haven't set it to anything yet - at that point answer is just an empty array. You need to set answer[i] = []; to set the first element of answer to be an empty array, and then you can use answer[i][j].
That will fit in your existing loop like this:
for (let i = 0; i < num.length; i++) {
answer[i] = []; // <--- add this
for (let j = 0; j < num[i]; j++, count++) {
answer[i][j] = arr[count];
}
}
Without testing it I believe you need to set answer[i] = [] before you loop your next array
answer[i] hasn't been created. You are trying to assign a value to something that doesn't exist. You need to create answer[i] like this:
answer[i] = new Array(num[i]);
So, the full code:
function infiniteLoop(arr, num) {
var answer = [];
var count = 0;
for (var i = 0; i < num.length; i++) {
answer[i] = new Array(num[i]);
for (var j = 0; j < num[i]; j++, count++) {
answer[i][j] = arr[count];
}
}
return answer;
}
document.write(infiniteLoop([1, 2, 3, 4, 5, 6, 7, 8, 9], [3, 3, 3]));
The problem is that answer[i] is undefined. The solution would be to add the following statement to the beginning of the first for loop:
answer[i] = [];
This should initialize answer[i] as an array, thus allowing you to set individual indices for it.

Output arrays in object in Javascript for spreadsheet

This is my code.
function order() {
//declare things
var order = [3, 2, 1, 0]
var testOne = [2, 3, 7, 4]
var testTwo = ["c", "b", "a", "d"]
//sort by order
var collatedArray = [];
for (var i = 0; i < order.length; i++)
{
index = order[i];
var collated =
{
test1 : testOne[index],
test2 : testTwo[index]
}
collatedArray.push(collated);
}
//Create output
var output = [];
for (i=0; i<collatedArray.length; i++)
{
output[i] = collatedArray[i].test1
}
return output
}
The output currently is only collatedArray[i].test1, which gives:
4, 7, 3, 2
If I change output[i] = collatedArray[i].test1 to test2, I get:
d, a, b, c
I just want to output the whole collatedArray (test1 and test2) so that I get:
4, 7, 3, 2
d, a, b, c
without the need for output variable, or converting back to arrays. The info is all there I just can't figure out how to get it out. Very new to coding, just not understanding what to do here :(
Thanks
Adjust output to an array containing two arrays; within last for loop populate each array within output with values at collatedArray[0][i].test1 and collatedArray[1][i].test2
// Create output
var output = [[], []];
for (i=0; i<collatedArray.length; i++)
{
output[0][i] = collatedArray[i].test1;
output[1][i] = collatedArray[i].test2;
}
function order() {
//declare things
var order = [3, 2, 1, 0]
var testOne = [2, 3, 7, 4]
var testTwo = ["c", "b", "a", "d"]
//sort by order
var collatedArray = [];
for (var i = 0; i < order.length; i++) {
index = order[i];
var collated = {
test1: testOne[index],
test2: testTwo[index]
}
collatedArray.push(collated);
}
//Create output
var output = [
[],
[]
];
for (i = 0; i < collatedArray.length; i++) {
output[0][i] = collatedArray[i].test1;
output[1][i] = collatedArray[i].test2;
}
return output
}
console.log(order())
There are several ways that you can do this, including storing each testNumber (testOne, testTwo, etc) in an object consisting of properties. Learn how objects work and you should, having observed your code here, easily be able to figure out how to loop through each property (which in your case will be arrays) of said Object to print out what you're looking for. If you can't figure it out, there are plenty of Stack Overflow Q&A's that cover this phenomenally well.
But for now, here is a simple alternative: an array of arrays.
https://jsfiddle.net/6r3hv3aq/7/
var testOne = [2,3,7,4];
var testTwo = ["c","b","a","d"];
var test = [testOne,testTwo];
for (var i = 0; i <= test.length-1; i++) {
console.log(test[i]);
}
Which will output exactly what you asked for:
[2, 3, 7, 4]
["c", "b", "a", "d"]
Note: When you click the jsfiddle link provided, you may have to refresh the page to see the appropriate results loaded into the console. Alternatively, leave the console open when you migrate to the link.
Since you're wanting this for a spreadsheet I am assuming you want a CSV output string that you can import into a spreadsheet program.
function row(source, sequence) {
var temp = new Array(sequence.length);
for (var i = 0; i < sequence.length; i++)
temp[i] = source[sequence[i]];
return temp.join(",")
}
function order() {
//declare things
var sequence = [3, 2, 1, 0];
var testOne = [2, 3, 7, 4];
var testTwo = ["c", "b", "a", "d"];
var rows = [];
rows.push(row(testOne, sequence));
rows.push(row(testTwo, sequence));
return rows.join("\r\n");
}
Here's a plunkr

Filtering arrays of complex objects with loops

I have two arrays of complex nexted objects that I'm looking for qualifying values within using loops and if statements as seen below. When I find a qualifying object, I need to filter that object out during the next go around of the loop. I'm trying to do that with an array as you can see here but it isn't working as the array starts over during each iteration of the loop. The following version is a simplified version of my code.
I want to update the values in array2 based on the if statement so that those values are not repeated in the nested loop. Instead my emptyArray remains empty instead of adding values from the array2 as elements of array2 are equal to elements of array.
To be clear, right now emptyArray remains empty and never filters array2. I'd like to see emptyArray collect value 2 at the start of the outer loop's second iteration then I'd like to see emptyArray collect value 4 at the start of the 4th iteration of the outer loop.
I'd want to filter each of these values from array2 as they become part of emptyArray so that they do not set off the if statement during the 6th and 8th iterations of the outer loop. I imagine that emptyArray = [2, 4] and array2 = [6, 8, 10] when the loops are finished.
Bottom line, I need emptyArray to collect the qualifying values and pass them back to var array2 for filtering as the loop processes. Remember this is a simplified version of the arrays, and underscore based solution would be very complicated for me to implement or for you to successfully suggest without much more detail.
My code:
var array = [1, 2, 3, 4, 1, 2, 3, 4];
var array2 = [2, 4, 6, 8, 10];
var emptyArray = [];
for (i = 0; i < array.length; i++){
var something = array[i];
var array2 = _.without(array2, emptyArray);
for (a = 0; a < array2.length; a++){
var value = array2[a];
if(something === value){
emptyArray.push(value);
break;
}
}
}
There are a few things wrong with your code, but the reason why you think that push isn't working is because you are overriding your array2 inside the loop.
The push never gets called because your for loop sees an empty array2 when you are doing var array2 = _.without(array2, emptyArray);
Basically var array2 = _.without(array2 /* this is empty, you just overrode it in this scope */, emptyArray); will always result in an empty array and your for loop will exit because length is array2.length === 0 from the start.
Also, you want to use _.difference instead of _.without
var array = [1, 2, 3, 4, 1, 2, 3, 4];
var array2 = [2, 4, 6, 8, 10];
var emptyArray = [];
for (var i = 0; i < array.length; i++) {
var something = array[i];
array2 = _.difference(array2, emptyArray);
for (var j = 0; j < array2.length; j++) {
var value = array2[j];
if (something === value) {
emptyArray.push(value);
break;
}
}
}
console.log("array2",array2);
console.log("emptyArray", emptyArray);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.5.0/lodash.js"></script>
array2 [6, 8, 10]
emptyArray [2, 4]
var array = [1, 2, 3, 4, 1, 2, 3, 4];
var array2 = [2, 4, 6, 8, 10];
var emptyArray = [];
for (var i = 0; i < array.length; i++) {
var something = array[i];
for (var j = 0; j < array2.length; j++) {
var value = array2[j];
if (something === value) {
array2 = _.without(array2, value);
break;
}
}
}

Categories

Resources