Can't push to array in JavaScript - 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]});

Related

javascript: how to convert array to tuple

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 ];

How to use Ramda remove to remove empty object from Array of objects?

Ramda remove : Ramda Repl link
The following is the given example, it removes specific numbers from an Array:
R.remove(2, 3, [1,2,3,4,5,6,7,8]); //=> [1,2,6,7,8]
Now I created an Array of objects, one being empty:
var objArray = [{id: 1, name: 'Leon'},{id: 2, name: 'Paulo'},{}];
When I try:
R.remove({}, objArray);
or
R.remove(R.isEmpty, objArray);
It returns a function:
Why would that be you suppose?
Figured it out:
const filteredAlerts = R.filter(Util.notEmpty, res.alerts);
I needed to filter by objects that are NOT empty.
This is my Util.notEmpty function:
const notEmpty = R.compose(R.not, R.isEmpty);

Convert javascript object to array of individual objects

I have the following object:
{English: 4, Math: 5, CompSci: 6}
How can I convert it to an array of objects, like:
[{English: 4}, {Math: 5}, {CompSci: 6}]
Can't find the answer anywhere. Thanks!!
Use Array#forEach over Object.keys(YOUR_OBJECT)
var input = {
English: 4,
Math: 5,
CompSci: 6
};
var op = [];
Object.keys(input).forEach(function(key) {
var obj = {};
obj[key] = input[key];
op.push(obj); //push newly created object in `op`array
});
console.log(op);
With newer JS, you could take Object.entries and map single properties.
var object = { English: 4, Math: 5, CompSci: 6 },
array = Object.entries(object).map(([k, v]) => ({ [k]: v }));
console.log(array);
Just loop over each of the keys in the object.
var oldObject = {English: 4, Math: 5, CompSci: 6};
var newArray = [];
// Loop over each key in the object
for (var key in oldObject) {
// Create a temp object
var temp = {};
// Set the key of temp
temp[key] = oldObject[key]
// Push it to the array
newArray.push(temp);
}
console.log(newArray)
you can directly assign object by {} but you must use [] quote for key value if not that will not worked
var obj = {English: 4, Math: 5, CompSci: 6};
var n_obj = [];
for(var i in obj){
n_obj.push({[i]:obj[i]});
}
console.log(n_obj);
You can turn the object into an array of key-value pairs using Object.entries and then map this array to smaller object created using Object.fromEntries from each individual key-value pair (the key part here is the wrapping in another array before passing to fromEntries):
Object.entries(obj).map(e => Object.fromEntries([e]))
The reverse way is similar: We create a big object using Object.fromEntries, and we pass in an array of key-value pairs. This array is created by flat-mapping (i.e. eliminating on extra layer of arrays) the array of objects to an array of key-value pairs we get from calling Object.entries on each small object. The key here is the flat-mapping, without it we would get an array of arrays of key-value pairs because we added that extra layer in the other conversion to separate the properties.
Object.fromEntries(arr.flatMap(o => Object.entries(o)))
You can use JSON.stringify(), String.prototype.match() with RegExp /".*"\:.*(?=,|})/, String.prototype.split() with RegExp /,/, Array.prototype.join() with parameter "},{", JSON.parse()
var obj = {English: 4, Math: 5, CompSci: 6};
var res = JSON.parse("[{"
+ JSON.stringify(obj)
.match(/".*"\:.*(?=,|})/g)[0]
.split(/,/)
.join("},{")
+ "}]");
console.log(res);

Convert ES6 Iterable to Array

Say you have an array-like Javascript ES6 Iterable that you know in advance will be finite in length, what's the best way to convert that to a Javascript Array?
The reason for doing so is that many js libraries such as underscore and lodash only support Arrays, so if you wish to use any of their functions on an Iterable, it must first be converted to an Array.
In python you can just use the list() function. Is there an equivalent in ES6?
You can use Array.from or spread syntax (...).
Example:
const x = new Set([ 1, 2, 3, 4 ]);
const y = Array.from(x);
console.log(y); // = [ 1, 2, 3, 4 ]
const z = [ ...x ];
console.log(z); // = [ 1, 2, 3, 4 ]
Summary:
Array.from() function, it takes an iterable as in input and returns an array of the iterable.
Spread syntax: ... in combination with an array literal.
const map = new Map([[ 1, 'one' ],[ 2, 'two' ]]);
const newArr1 = [ ...map ]; // create an Array literal and use the spread syntax on it
const newArr2 = Array.from( map ); //
console.log(newArr1, newArr2);
Caveat when copying arrays:
Be cognizant of the fact that via these methods above only a shallow copy is created when we want to copy an array. An example will clarify the potential issue:
let arr = [1, 2, ['a', 'b']];
let newArr = [ ...arr ];
console.log(newArr);
arr[2][0] = 'change';
console.log(newArr);
Here because of the nested array the reference is copied and no new array is created. Therefore if we mutate the inner array of the old array, this change will be reflected in the new array (because they refer to the same array, the reference was copied).
Solution for caveat:
We can resolve the issue of having shallow copies by creating a deep clone of the array using JSON.parse(JSON.stringify(array)). For example:
let arr = [1, 2, ['a', 'b']]
let newArr = Array.from(arr);
let deepCloneArr = JSON.parse(JSON.stringify(arr));
arr[2][0] = 'change';
console.log(newArr, deepCloneArr)
You can use the Array.from method, which is being added in ES6, but only supports arrays and iterable objects like Maps and Sets (also coming in ES6). For regular objects, you can use Underscore's toArray method or lodash's toArray method, since both libraries actually have great support for objects, not just arrays. If you are already using underscore or lodash, then luckily they can handle the problem for you, alongside adding various functional concepts like map and reduce for your objects.
The following approach is tested for Maps:
const MyMap = new Map([
['a', 1],
['b', 2],
['c', 3]
]);
const MyArray = [...MyMap].map(item => {
return {[item[0]]: item[1]}
});
console.info( MyArray ); //[{"a", 1}, {"b", 2}, {"c": 3}]
<Your_Array> = [].concat.apply([], Array.from( <Your_IterableIterator> ));
You could also do the following, but both approaches are certainly not recommendable (merely a proof-of-concept for completeness):
let arr = [];
for (let elem of gen(...)){
arr.push(elem);
}
Or "the hard way" using ES5 + generator function (Fiddle works in current Firefox):
var squares = function* (n) {
for (var i = 0; i < n; i++) {
yield i * i;
}
};
var arr = [];
var gen = squares(10);
var g;
while (true) {
g = gen.next();
if (g.done) {
break;
}
arr.push(g.value);
}

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