JavaScript object dimensions - javascript

I want to define a two-dimensional object, but I do not succeed.
var b = [1,2,3,4,5,6,7,8];
var a = {};
var c = ["baslik","resim","icerik","links"];
for(i=0;i<2;i++){
for(s=0;s<4;s++){
a[c[s]]=b[s];
}
}
document.writeln(JSON.stringify(a));
Output:
{"baslik":1,"resim":2,"icerik":3,"links":4}
I want this output:
{"baslik":1,"resim":2,"icerik":3,"links":4},
{"baslik":5,"resim":6,"icerik":7,"links":8}

Try:
var a = []; //Must be a array
var b = [1,2,3,4,5,6,7,8];
var c = ["baslik","resim","icerik","links"];
for(i=0;i<2;i++){
var obj = {} //Object
for(s=0;s<4;s++){
obj[c[s]]=b[s+4*i];
}
a.push(obj)
}
document.writeln(JSON.stringify(a));

Try like this
var b = [1,2,3,4,5,6,7,8];
var a = [];
var c = ["baslik","resim","icerik","links"];
var n= Math.floor(b.length/c.length);
var k=0;
for(var i=0;i<n;i++){
var entity={};
for(var j=0;j<c.length;j++){
entity[c[j]]= k<b.length ? b[k++] : 0;
}
a.push(entity);
}
console.log(JSON.stringify(a));

Try:
var b = [1, 2, 3, 4, 5, 6, 7, 8];
var a = [];
var c = ["baslik", "resim", "icerik", "links"];
var n = c.length;
b.reduce(function(x, num, i) {
x[c[i % n]] = num;
if (((i + 1) % n) == 0) {
a.push(x);
x = {};
}
if ((i + 1) == b.length) return a;
return x;
}, {})
console.log(JSON.stringify(a));

Related

Why do I get a NaN value and the end of my rubiks cube scramble generator when I remove duplicates?

I am developing a Rubik cube app for fitbit versa and I run into the problem of removing duplicates from arrays as I get a NaN error when combining the arrays once the duplicates have been removed from the end of the list and it only happens when I splice at the end of the array and I cant figure out the reason why this isnt working
function getScramble(number_of_moves, faces, modifiers, scramble_faces, scramble_modifiers, scramble) {
for (var i = 0; i < number_of_moves; i++) {
var sample = faces[Math.floor(Math.random() * faces.length)];
var mod = modifiers[Math.floor(Math.random() * modifiers.length)];
scramble_faces[i] = sample;
scramble_modifiers[i] = mod;
if (scramble_faces[i] == scramble_faces[i - 1]) {
scramble_faces[i] = faces[Math.floor(Math.random() * faces.length)];
}
}
removeDuplicates(scramble_faces, scramble_modifiers)
for (var i = 0; i < number_of_moves - 2; i++) {
scramble[i] = scramble_faces[i] + scramble_modifiers[i]
}
console.log(scramble);
let demotext = document.getElementById("demotext");
demotext.text = scramble;
scramble = [];
scramble_faces = [];
scramble_modifiers = [];
}
function threebythree() {
var faces = ["U", "D", "L", "R", "F", "B"];
var modifiers = ["", "'", "2"];
var scramble_faces = [];
var scramble_modifiers = [];
var scramble = [];
var number_of_moves = 22;
let Title1 = document.getElementById("title");
Title1.text = "3x3"
getScramble(number_of_moves, faces, modifiers, scramble_faces, scramble_modifiers, scramble, Title1)
}
function removeDuplicates(arr, arr2, number_of_moves) {
var t = 0;
var new_arr = arr;
var new_arr2 = arr2;
for (var i = new_arr.length - 1; i >= 0; i--) {
if (new_arr[i] === new_arr[i - 1]) {
new_arr.splice(i, 1);
new_arr2.splice(i, 1);
}
}
arr = new_arr;
arr2 = new_arr2;
new_arr = [];
new_arr2 = [];
new_arr.pop();
new_arr2.pop();
console.log(arr);
console.log(arr2);
}
The lengths of scramble_faces and scramble_modifiers is initially number_of_moves. But after you remove duplicates from them, it can be shorter. But you still use number_of_moves in the limit in the next for loop. So when you try to add the elements that no longer exist you get undefined. undefined + undefined == NaN.
You should use the length of one of the arrays instead:
function getScramble(number_of_moves, faces, modifiers, scramble_faces, scramble_modifiers, scramble) {
for (var i = 0; i < number_of_moves; i++) {
var sample = faces[Math.floor(Math.random() * faces.length)];
var mod = modifiers[Math.floor(Math.random() * modifiers.length)];
scramble_faces[i] = sample;
scramble_modifiers[i] = mod;
if (scramble_faces[i] == scramble_faces[i - 1]) {
scramble_faces[i] = faces[Math.floor(Math.random() * faces.length)];
}
}
removeDuplicates(scramble_faces, scramble_modifiers)
for (var i = 0; i < scramble_faces.length - 2; i++) {
scramble[i] = scramble_faces[i] + scramble_modifiers[i]
}
console.log(scramble);
let demotext = document.getElementById("demotext");
demotext.text = scramble;
scramble = [];
scramble_faces = [];
scramble_modifiers = [];
}

Array Transpose: Error reading property from "Undefined"

Getting an error message for the below code that works to get Values from several cells in my order entry tab named POTemplate and log them in my POHistory tab the serves to compile a list of all order detail entries. As the debugger gets to the bottom of the below code, I get an error message stating: "Cannot Read Property 0.0 from Undefined"
function submit() {
var app = SpreadsheetApp;
var tplSheet = app.getActiveSpreadsheet().getSheetByName("POTemplate");
var tplFRow = 22, tplLRow = tplSheet.getLastRow();
var tplRowsNum = tplLRow - tplFRow + 1;
var tplFCol = 1, tplLCol = 16;
var tplColsNum = tplLCol - tplFCol + 1;
var rangeData = tplSheet.getRange(22, 1, 5, 15).getValues();
var colIndexes = [0, 3, 10, 12, 15];
var fData = filterByIndexes(rangeData, colIndexes);
var target = "POHistory";
var targetSheet = app.getActiveSpreadsheet().getSheetByName(target);
var tgtRow = targetSheet.getLastRow() + 1;
var tgtRowsNum = fData.length - tgtRow + 1;
var tgtCol = 1;
var tgtColsNum = fData[0].length - 1 + 1;
targetSheet.getRange(tgtRow, tgtCol, tgtRowsNum,
tgtColsNum).setValues(fData);
}
function filterByIndexes(twoDArr, indexArr) {
var fData = [];
twoDArr = twoDArr.transpose();
for(var i = 0; i < indexArr.length; i++) {
fData.push(twoDArr[indexArr[i]]);
}
return fData.transpose();
}
Array.prototype.transpose = function() {
var a = this,
w = a.length ? a.length : 0,
h = a[0] instanceof Array ? a[0].length : 0;
if (h === 0 || w === 0) {return [];}
var i, j, t = [];
for (i = 0; i < h; i++) {
t[i] = [];
for (j = 0; j < w; j++) {
t[i][j] = a[j][i];
}
}
return t;
}

add elements of two arrays - the best way

var a = "1:2:3:4";
var b = "0:1:5:2";
I want at the end:
var c = "1:3:8:6";
meaning, the numbers are summed by column.
my solution is:
var i, k;
var a_arr = a.split(':');
var b_arr = b.split(':');
for (i=0;i<a_arr.length;i++){
and here again another loop over b_arr
}
eeh ok, I dont have solution.. what is the cutest way to do this?
You could just map it and return the added values ?
var a = "1:2:3:4";
var b = "0:1:5:2";
var c = a.split(':').map(function(x, i) {
return (+x) + (+b.split(':')[i]);
}).join(':');
document.body.innerHTML = '<pre>' + c + '</pre>';
or splitting outside the map
var c = (function(y) {
return a.split(':').map(function(x, i) {
return (+x) + (+y[i]);
}).join(':')
})(b.split(':'));
Building on my comment, you can use i to index both the arrays:
var i, k;
var a_arr = a.split(':');
var b_arr = b.split(':');
var c_arr = [];
for (i=0;i<a_arr.length;i++){
c_arr.push(parseInt(a_arr[i], 10) + parseInt(b_arr[i], 10));
}
//And use join to get the final result
var c = c_arr.join(":");
You can use index i to add the simply use join()
var a = "1:2:3:4";
var b = "0:1:5:2";
var c = [];
var i, k;
var a_arr = a.split(':');
var b_arr = b.split(':');
for (i=0;i<a_arr.length;i++){
c[i] = parseInt(a_arr[i], 10) + parseInt(b_arr[i], 10); //Add using index
}
console.log(c.join(':')); //Use Join
http://jsfiddle.net/fLavfcjz/1/
Use .map() and don't forget parseInt() otherwise the numbers will considered as strings.
var a = "1:2:3:4";
var b = "0:1:5:2";
var arrayA = a.split(':');
var arrayB = b.split(':');
var combinedArr = arrayA.map(function (v, i) {
return parseInt(v,10) + parseInt(arrayB[i],10); // or return (+v) + (+arrayB[i]);
});
console.log(combinedArr.join(':')); //1:3:8:6
Try this
var a = "1:2:3:4";
var b = "0:1:5:2";
var a_arr = a.split(':');
var b_arr = b.split(':');
var c_arr = [];
for (i in a_arr) {
var to_add = 0;
if (b_arr[i] != undefined) to_add = b_arr[i];
c_arr[i] = a_arr[i] + to_add;
}
You don't need a second loop. The resulting array of the following snippet will have the length of the shorter input array.
var a = '1:2:3:4'
var b = '0:1:5:2'
var aArray = a.split(':')
var bArray = b.split(':')
var result = []
for (
var i = 0, aLength = aArray.length, bLength = bArray.length;
i < aLength && i < bLength;
i++
) {
result.push(Number(a[i]) + Number(b[i]))
}
result = result.join(':')
console.log(result)

Js Objects Links for one?

I want to make object with different key 'number' with values from arr;
var arr = [1,2,4],
q = {},
a = { number : null };
for (i=0;i<3;i++) {
q[i] = a;
q[i].number = arr[i];
}
But with this i got 3 same objects.
I tried to make a closure like
var arr = [1,2,4],
q = {},
a = { number : null };
for (i=0;i<3;i++) {
(function(number) {
q[number] = a;
q[number].number = arr[number];
})(i)
}
but result is the same. What i am doing wrong?
You already define object a. And when you write a to q[i] it just write pointer to this object. Fixed code:
var arr = [1,2,4],
q = {};
for (i = 0; i < 3; i++) {
q[i] = {};
q[i].number = arr[i];
}
And if cleans up here:
var array = [1, 2, 4],
q = Object.create(null);
array.forEach(function(value, index) {
$.extend(q[index], {
number: value
});
});
.forEach()

String to Object literal

Is it possible to convert a string var:
data="data1,data2,data3,data4"
to an object literal
data={
"data1":"data2",
"data3":"data4"
}
Thank you!
var arr = data.split(',');
var parsedData = {};
for (var i = 0; i < arr.length; i += 2) {
parsedData[arr[i]] = arr[i + 1];
}
This is trivial:
function object_from_string(str) {
var parts = str.split(','),
obj = {};
for(var i = 0, j = parts.length; i < j; i+=2;) {
obj[parts[i]] = parts[i+1];
}
return obj;
}
var data = "data1,data2,data3,data4";
var obj = object_from_string(data);
for(var k in obj) {
if(obj.hasOwnProperty(k)) {
console.log(k + ' = ' + obj[k]);
}
}
Output:
data1 = data2
data3 = data4

Categories