Combine 2 array into json with different sizes - javascript

I have 2 arrays in the below:
sonuc_X = [ 41.01766, 41.01746, 41.05877, 41.05974, 41.04383, 41.03693 ];
var labels = ["lat"];
I also have merge processing below:
var obj_X = {};
for (var j = 0; j < labels.length; j++) {
obj_X[labels[j]] = sonuc_X[j];
}
var asJSON = JSON.stringify(obj_X);
console.log(asJSON);
when I combine two sequences at the json, the following result comes out:
{"lat":41.01766}
I expect:
[ "lat":41.01766, "lat":41.01746, "lat":41.05877, "lat":41.05974, "lat":41.04383, "lat":41.03693 ]
?

You could iterate the data and build new objects with the wanted keys.
var data = [41.01766, 41.01746, 41.05877, 41.05974, 41.04383, 41.03693],
keys = ["lat", "lng"],
result = data.reduce(function (r, v, i) {
if (i % keys.length === 0) {
r.push({});
}
r[r.length - 1][keys[i % keys.length]] = v;
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related

Nested matrix and nested loop problem not working

This should be the input and output:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]
The returned output is actually the same as the input. What am I doing wrong?
var rotate = function(matrix) {
let result = matrix;
let i = 0;
let index = matrix.length - 1;
for (let x of matrix) {
for (let n of x) {
result[i][index] == n;
if (i<matrix.length-2)
i++;
}
index--;
}
console.log(result);
return result;
};
var list= [[1,2,3],[4,5,6],[7,8,9]];
rotate(list);
const matrix = [
[1,2,3],
[4,5,6],
[7,8,9]
];
const rotate = (m) => {
const n = m.length;
const r = [ ...m.map(a => []) ];
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
r[i][j] = m[n - j - 1][i];
}
}
return r;
}
const result = rotate(matrix);
console.log(result);

Multidimensional array JS snippest

In below given JavaScript code I am unable achieve expected output. please help me to get resolve the given code.
Please check for the expected output.
In below given JavaScript code I am unable achieve expected output. please help me to get resolve the given code.
Please check for the expected output.
$(document).ready(function(){
var record = [];
var idarr = ['5','2','-','3','-'];
var jobidarr = [];
var userid = 32;
var newlogtimedata = ["2020/11/14 13:29:30","-","2020/10/10 13:33:49","-"];
var newlogtimedataupdate = [];
var logcnt = 1;
var j=0;
for(var i = 0; i < newlogtimedata.length; i++){
if(newlogtimedata[i] != "-"){
newlogtimedataupdate.push(newlogtimedata[i]);
}
}
for(var i = 0; i < idarr.length; i++){
if(idarr[i] == "-"){
logcnt++;
}
else{
//for(var j = 0; j < idarr.length; j++){
record[[j]] = new Array();
record[[j]].push(parseInt(idarr[i]));
record[[++j]]= new Array();
/* record[[j]].push(JSON.stringify(parseInt(userid)));
record[[j]].push("-");
record[[++j]] = new Array();
record[[j]].push(newlogtimedataupdate[logcnt-1]);
record[[j]].push("-"); */
j++;
//}
}
}
console.log("record:::", record);
});
/*
expected output will be
record:::
[ [5, 32, ['2020/11/14 13:29:30','-'],
[2, 32, ['2020/11/14 13:29:30','-'],
[3, 32, ['2020/10/10 13:33:49','-'] ]; */
I believe this your desired result, not sure what it's supposed to represent though:
var idarr = ['5', '2', '-', '3', '-'];
var userid = 32;
var newlogtimedata = [
"2020/11/14 13:29:30", "-",
"2020/10/10 13:33:49", "-"
];
const result = idarr.reduce((a, c, i) => {
if (c === '-') return a;
a.push([
parseInt(c, 10),
userid,
[
newlogtimedata[i] === '-' ? newlogtimedata[i - 1] : newlogtimedata[i],
'-'
]
]);
return a;
}, []);
console.log(result)
Try this:
for(var j = 0; j < idarr.length; j++){
record.push([
parseInt(idarr[i]),
userid,
[newlogtimedataupdate[logcnt - 1], '-']
]);
}
To access data inside multi-dimensional arrays, it looks like this myArray[2][1].
Example:
Here's a multi-dimensional array with some random values:
let myArray = [
['cake', 'cookie'],
['car', 'plane', 'train']
];
To access the elements inside myArray, you first select the index of one of the inner arrays. That means myArray[0] looks like: ['cake', 'cookie'], and now you can select the elements inside the inner array like so: myArray[0][1] (which is 'cookie').
You could use two indices for the arrays and pick an item as long as no sparator is coming.
let idarr = ['5', '2', '-', '3', '-'],
userid = 32,
newlogtimedata = ["2020/11/14 13:29:30", "-", "2020/10/10 13:33:49", "-"],
SEPARATOR = '-',
record = [],
i = 0,
j = 0;
while (i < idarr.length && j < newlogtimedata.length) {
record.push([idarr[i], userid, [newlogtimedata[j], '-']]);
if (idarr[i + 1] === SEPARATOR && newlogtimedata[j + 1] === SEPARATOR) {
i += 2;
j += 2;
continue;
}
if (idarr[i + 1] !== SEPARATOR) i++;
if (newlogtimedata[j + 1] !== SEPARATOR) j++;
}
console.log(record);
.as-console-wrapper { max-height: 100% !important; top: 0; }

JS variable which is for an object's value index does not return any value

Total lost.
What I want to do is get the array like under below.
0: {run: 'sam'. swim: 'ham'},
1: {run: 'tom', swim:'bill'},
2: {run: 'jim', swim: 'sam},
......
but when I put the code here, obj[name1[o]] = name2[some(name2)];, especially value part, doesn't work.
why I cannot use a variable for the index of an object's value in this sentence?
const arr = [];
const obj = {}
var name1 = ['run','swim'];
var name2 = ['sam','ham','tom','bill','jim'];
function some(a){
for(var n = 0; n < a.length; n++){
n //simplified calculating
}
}
for(var a = 0; a<3; a++){
arr[a] = obj;
for(var o=0; o<2; o++){
obj[name1[o]] = name2[some(name2)];
}
}
console.log(arr);
You could take all names and all keys and take a calculated length for iteration.
The value are taken with the reminder operator % and the length of the array to prevent undefined values.
var keys = ['run', 'swim'],
names = ['sam', 'ham', 'tom', 'bill', 'jim'],
result = [],
length = Math.ceil(names.length / keys.length) * keys.length;
for (let i = 0; i < length; i++) {
let j = Math.floor(i / keys.length);
if (!result[j]) result[j] = {};
result[j][keys[i % keys.length]] = names[i % names.length];
}
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Finding unique pairs in array

Given this input [3,1,2] I want to have this output [ [ 1, 1 ], [ 1, 2 ], [ 1, 3 ], [ 2, 2 ], [ 2, 3 ], [ 3, 3 ] ]
Its the unique pairs ([1,2] == [2,1])
Currently I've made that
const arr = [3,1,2];
const pairBuilder = (left, index, collection) =>
collection.slice(index).map(right => [left, right]);
const pairs = arr.sort().flatMap(pairBuilder);
console.log(pairs)
This code is functional, but I wonder if there is not a better way (in terms of performances) to achieve this ? I've though of using lodash to improve sorting / mapping (with chain), but my question is more about algorithm improvement.
You could use a Generator with a function* and slice the array for getting only unique pairs.
function* getPairs(array, left) {
var i = 0;
while (i < array.length) {
if (left) yield [left, array[i]];
else yield* getPairs(array.slice(i), array[i]);
i++;
}
}
var array = [1, 2, 3];
console.log([...getPairs(array)]);
.as-console-wrapper { max-height: 100% !important; top: 0; }
A classic approach.
function getPairs(array) {
var i, j, result = [];
for (i = 0; i < array.length; i++) {
for (j = i; j < array.length; j++) {
result.push([array[i], array[j]]);
}
}
return result;
}
var array = [1, 2, 3];
console.log(getPairs(array));
.as-console-wrapper { max-height: 100% !important; top: 0; }
This is a naive and slow approach.
But i beleive it is faster than accepted answer and answer in the question.
It generates less new objects overhead and requires less memory.
Naive algorithm doesn't use recursion. so does not face recursion limit (50 by default)
Also i beleive it's still readable and easy to understand
const inp = [3, 1,2];
function genPair(inp) {
const length = inp.length;
const sorted = inp.sort();
const result = [];
for (let i = 0; i < length; i++) {
for (let j = i; j < length; j++) {
result.push([sorted[i], sorted[j]]);
}
}
return result;
}
const r = genPair(inp);
console.log(r);
link to js perf
https://jsperf.com/find-dups/1
Accepted answer in IE11 60% slower and in Chrome 10% slower

Return the index of largest sum within array

I'm a bit of a newbie when it comes to JavaScript. I'm working on a bit of a coding problem, and I'm running into a wall. Here's the code I'm having trouble with so far:
function creditCardTest (creditCardNumbers) {
var creditCardNumbers = [
'7629-1648-1623-7952',
'4962-1694-2293-7910',
'9999-9999-9999-9999', /*For test purposes*/
'4921-2090-4961-7308'
]
var sumArray = [ ]; //parallel to creditCardNumbers array
var largestValue = 0;
var locationOfLargest = 0;
var itemSum = 0;
for(var i = 0; i < creditCardNumbers.length; i++) {
var creditCardItem = creditCardNumbers [ i ];
/*console.log(creditCardItem); For test purposes*/
itemSum = 0; //required for functionality
for (var j = 0; j < creditCardItem.length; j++) {
var stringChar = creditCardItem.charAt( j );
/*console.log(stringChar); For test purposes*/
if ( stringChar >= '0' && stringChar <= '9' ) {
itemSum += parseInt(stringChar);
/*console.log(parseInt(stringChar)); For test purposes*/
}
}
sumArray[ i ] = itemSum;
console.log(sumArray[ i ]); /*required for functionality*/
}
if (!largestValue || sumArray[ i ] > largestValue) {
largestValue = sumArray[ i ];
locationOfLargest = i;
}
console.log(locationOfLargest);
}
creditCardTest( );
I'm looking to return the largest index in an array, but I'm only getting the 0th index as a result. Any input?
Here is a little fiddle
var largestValue = 0,
locationOfLargest = 0,
sumArray = [1, 100, 909, 8, 91098, 923823];
for (var i = 0; i < sumArray.length; i++) {
if (!largestValue || sumArray[i] > largestValue) {
largestValue = sumArray[i];
locationOfLargest = i;
}
}
console.log(locationOfLargest, largestValue);
or even a quicker solution:
var arr = [1, 100, 909, 8, 91098, 923823],
index = arr.indexOf(Math.max.apply(Math, arr));
console.log(index);
You could use a step by step approach
get first an array of digits
add the digits
get the index of max sum.
var data = ['7629-1648-1623-7952', '4962-1694-2293-7910', '9999-9999-9999-9999', '4921-2090-4961-7308'],
index = data.
map(a => a.match(/\d/g)).
map(a => a.reduce((a, b) => +a + +b)).
reduce((r, a, i, aa) => !i || aa[r] < a ? i : r, -1);
console.log(index);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Categories