javascript: how to convert array to tuple - javascript

I have strange requirement in which i am using javascript.
I have json file from where i extract the values leaving keys. when i extract values I have them in array. I should change the array to tuple
in Python, we have and array and tuple concepts. But i am not sure about javascript.
Can anyone help one this
sample json
[ {a:1 , b:2}, {c: 3, D:4} ]
I am able to extract values for json array
my result is :
[1, 2]
and i want it to be as
(1,2)
where i need to pass the (1,2) as arguments to java program

let b = [1, 2, 3];
let ids = `('${b.join("','")}')`;
console.log(ids);
// "('1','2','3')"

As #vlaz write, there are no tuples but you have to use array like so:
var data = [ {a:1 , b:2}, {c: 3, D:4} ];
var result = [ data[0].a, data[0].b ];

Related

Can't push to array in JavaScript

I get an error when I run this code:
var array = [];
array.push(["one"]:[1,2,3]);
array.push(["two"]:[4,5,6]);
I want my array to look like this in the end:
{"one": [1,2,3], "two": [4,5,6]};
I don't know how to fix this error, I want to use push.
An associative array in JavaScript is an object, so you can't use array.push as that's not valid there. You'd just want: array["one"] = [1,2,3]
var array = {};
array.one = [123, 123];
array.two = [123, 123];
console.log(array)
output
{
one: [
123,
123
],
two: [
123,
123
]
}
You should be opting for something like below. Using push, you will not achieve your desired output.
let obj = {};
const item1 = {
["one"]: [1, 2, 3]
}
const item2 = {
["two"]: [4, 5, 6]
}
obj = {
...obj,
...item1,
...item2
}
The reason you got the error is because you are missing object wrapper notation in your push {}
array.push({["one"]:[1,2,3]});
array.push({["two"]:[4,5,6]});
but as said, this will not give the desired output: {"one": [1,2,3], "two": [4,5,6]};
You must first create the object, assign values into the object, then push it into the array. Refer to this post for more information.
push object into array
Javascript doesn't have Associative Arrays like other languages, but it have Objects, that is similar.
var object = {};
object.one = [1,2,3];
// or if the key name comes from a variable:
var key = "two";
object[key] = [4,5,6];
"one" is an object not an array. remove the parenthesis from there. See below code:
array.push({"one":[1,2,3]});
array.push({"two":[4,5,6]});

Adding array of arrays dynamically in javascript

I am trying to add array of arrays dynamically in javascript. I need the data in the following format -
var dataArray = [[],[],[],.....,[]];
How can I initialize this kind of array? Suppose if I have three arrays to be added, I can initialize as follows -
var dataArray = [[],[],[]];
This will accept only three records to be added. But, what should I do in case of adding large number of arrays? Here I cannot know the amount of data I get as input.
I have tried using concat() and merge() methods, these are adding contents directly in to a single array, but that is not what I wanted.
Can any one please help me out on this?
You can build or add an array into an array like this:
var dataArray = [];
dataArray.push([1,2,3]);
dataArray.push([3,4,5]);
console.log(dataArray); // [[1,2,3], [3,4,5]]
Or, if you want to add elements to the sub-arrays:
var dataArray = [];
dataArray.push([1,2,3]);
dataArray.push([3,4,5]);
dataArray[0].push(4);
dataArray[1].push(9);
console.log(dataArray); // [[1,2,3,4], [3,4,5,9]]
You initialize a sub-array by assigning an array to the element of the outer array. You can then use array operations directly on the sub-array element:
// create a sub-array element
dataArray[2] = [];
dataArray[2].push(8);
dataArray[2].push(7);
console.log(dataArray[2]); // [8,7]
console.log(dataArray); // [[1,2,3,4], [3,4,5,9], [8,7]]
The key thing it appears you don't understand is that an array of arrays is just that. It's an outer array where each element in the outer array is itself an array. You use ordinary array methods to operate on either the outer array or the inner arrays. To operate on an inner array, you fetch that element from the outer array and then just treat it as an array. For example:
var dataArray = [];
dataArray.push([1,2,3]);
dataArray.push([3,4,5]);
console.log(dataArray); // [[1,2,3], [3,4,5]]
var innerArray = dataArray[0];
console.log(innerArray); // [1,2,3]
innerArray.push(12);
console.log(innerArray); // [1,2,3,12]
innerArray.legnth = 2;
console.log(innerArray); // [1,2]
innerArray.push(9,8,7);
console.log(innerArray); // [1,2,9,8,7]
innerArray.splice(1,2);
console.log(innerArray); // [1,8,7]
You have wrote "I am trying to add array of arrays dynamically in javascript"
The simple way is using Array.prototype.push method:
var arr1 = [1,2], arr2 = [3,4], arr3 = [5,6], arr4 = [7,8], arr5 = [9,10],
dataArray = [];
[].push.apply(dataArray, [arr1, arr2, arr3, arr4, arr5]);
console.log(JSON.stringify(dataArray, 0, 4));
The console.log output:
[
[
1,
2
],
[
3,
4
],
[
5,
6
],
[
7,
8
],
[
9,
10
]
]
There are tons of way you can do this. A simple one could be
var arrayN = n => Array(n).fill([])
document.write("<pre>" + JSON.stringify(arrayN(10)) + "</pre>")
On another thinking if you already have arrays of arrays then the most simplified way of concatenating them in place should be using the new spread operator like;
var arr = [[1,2,3],[1,3,5]],
brr = [[3,2,1],[7,8,9]];
arr.push(...brr);
document.write("<pre>" + JSON.stringify(arr) + "</pre>");

Javascript table multidimension

Hello i'm begignner at javascript, I wrote the code below and get this error in my console "SyntaxError: Unexpected token ,"
var tab1=[{0,2,4,6,8},{1,3,5,7}];
console.log(tab1[0][0]);
Please change the curly to square brackets:
var tab1 = [[0, 2, 4, 6, 8], [1, 3, 5, 7]];
[] are used for arrays, {} are used for objects.
Examples:
array = ['a', 'b', 'c'];
object = { property: 'one', key: 'two' };
{} is for creating objects; it expects key: value pairs inside, which are called property initializers.
[] is for creating arrays.
So if you want to create an array of arrays (JavaScript doesn't have two-dimensional arrays, but arrays of arrays work just as well), use nested []:
var tab1=[[0,2,4,6,8],[1,3,5,7]];
Just for completeness, here's an example of an object rather than array:
var obj = {
question: "Life, the Universe, and Everything",
answer: 42
};
The reason for the error is that you just had 0,2 and it was expecting a : after the 0. (Literal numbers are valid object keys, which is why the 0 wasn't the problem.)

How to flatten an array of objects into arrays for each object parameter?

I have an array of objects like this:
[
{
p1: 1
p2: 2
},
{
p1: 3
p2: 4
}
]
I would like to flatten this into an array (maintaining order) for each property on the object:
[1, 3] and [2, 4]
Preferably these would be stored in a dictionary with the property as the key:
{
p1: [1, 3],
p2: [2, 4]
}
Is there a non brute force method of doing this in javascript? I am already using both jQuery and Underscore.js if those libraries are any help here.
My current plan is to iterate through all of the objects in the array and manually add each property value to its corresponding array. I'm interested to know if there is more interesting way of doing this.
If the properties are reliably the same on each object, you can use underscore like this.
var keys = _.keys(arr[0]);
var newObj = _.reduce(keys,function(obj,key){
obj[key] = _.pluck(arr,key)
},{});
//newObj will now be in the requested format
If the properties are different on different objects, you'll need to do some additional logic to get the complete list of properties to iterate over.
Something like that:
var result = data.reduce(function(acc, x) {
Object.keys(x).forEach(function(k) {
acc[k] = (acc[k] || []).concat([x[k]])
})
return acc
},{})
console.log(result)
//^ {
// p1: [1, 3],
// p2: [2, 4]
// }
But note that object keys have no order, and the result is up to each implementation. You may have to sort the resulting arrays if you need a specific order.

Is there a multidimensional array type in Javascript?

I have programmed in Microsoft Small Basic in the past, which can have arrays like this:
Array[1][1] = "Hello"
Array[1][2] = "Hi"
Array[1][2] = "Hey"
Now, in Javascript, I know how to create a single array (var Array = New Array()) but are there any array types like the ones above?
There are no true multidimensional arrays in JavaScript. But you can create an array of arrays like you have done.
JavaScript's arrays are just objects with a special length property and a different prototype chain.
Yes, you need to create an array of arrays:
var x = new Array(3);
x[0] = new Array(3);
x[1] = new Array(3);
x[2] = new Array(3);
x[0][0] = "Hello";
etc.
Remember that indexing is zero-based.
Edit
Or:
var x=[];
x[0] = [];
x[1] = [];
x[2] = [];
...
x[0][0] = "Hello";
etc.
You can achieve this:
var o = [[1,2,3],[4,5,6]];
Also you can use the fact that objects in javascript are dictionaries:
var o;
o["0"] = {'0':1, '1':2, '1':3};
var x = o["0"]["1"]; //returns 2
The easiest way would be to just declare an array, and initialize it with a bunch of other arrays. For example:
var mArray = [
[1,2,3],
[4,5,6]
];
window.alert(mArray[1][1]); //Displays 5
As others have pointed out, this is not actually a multi-dimentional array in the standard sense. It's just an array that happens to contain other arrays. You could just as easily have an array that had 3 other arrays, an int, a string, a function, and an object. JavaScript is cool like that.
You can create arrays statically in JS like this:
var arr = [
[1, 2, 3, 4],
[8, 6, 7, 8]
];
Note that since this is not a true "multidimentional array", just an "array of arrays" the "inner arrays" do not have to be the same length, or even the same type. Like so:
var arr = [
[1, 2, 3, 4],
["a", "b"]
];

Categories