Creating array collection in JavaScript? - javascript

Is it possible to create an array collection in JavaScript? If so, how can I do that? If I have some data : 1- 5 for example.

I actually do not quite understand what you want to do, but you can create a Javascript array containing the numbers 1 to 5 like this:
var myArray = [1, 2, 3, 4, 5];

Here is the simple way to create an array collection
var createCollection = function() {
//Define a blank array
this.employee = [];
//Creating first object and push it into array
var emp1 = {
'Name': 'ABC',
'Age': 30,
'Profession': 'Software'
};
this.employee.push(emp1);
//Creating Second object and push it into array
var emp2 = {
'Name': 'CDE',
'Age': 21,
'Profession': 'Advocate'
};
this.employee.push(emp2);
//Creating Third object and push it into array
var emp3 = {
'Name': 'RTY',
'Age': 22,
'Profession': 'Teacher'
};
this.employee.push(emp3);
};
var createCollection = new createCollection();
//returns the length of the collection
alert(createCollection.employee.length);
//You can access the value from Array collection either through indexing or looping
alert(createCollection.employee[0].Name);
alert(createCollection.employee[0].Age);
alert(createCollection.employee[0].Profession);

A-Z of javascript Arrays
check this link
If you want to populate an array
var tmpArray = new Array (4);
tmpArray [0] = "a";
tmpArray [1] = "b";
tmpArray [2] = "c";
tmpArray [3] = "d";
Or
var tmpArray= new Array ("a", "b", "c", "d");

If you want a more complex collection of data you can use the data.js abstraction library.
If your more specific in what you want I can show you an example.

You can create object:
var obj = {
my1 : 'data',
my2 : 'other'
};
Or
var array = ['data', 'other'];
Access all data you can
for(var key in array) {
item = array[key];
}
for(var key in obj) {
item = obj[key];
}

Related

Is it possible to using forEach method for two arrays in same time?

var arr1 = [1,2,3,4,5];
var arr2 = ["a","b","c","d","e"];
Let's assume that I want to create a list like
1 a
2 b
3 c
4 d
5 e
by using template literal.
let x;
x = document.createElement('li');
x.innerHTML += `<span>${<arr1 index>}</span> <span>${<arr2 index>}</span>`
How can I do that ? Can we use forEach for two arrays in same time ?
This would be more like flatten(zip(arr1, arr2)). There is no built-in zip though you can very easily make it and you can see Array.flat here: MDN: Array.flat.
const arr1 = [1, 2, 3, 4, 5];
const arr2 = ["a", "b", "c", "d", "e"];
const flatten = arr => arr.flat();
const zip = (a, b) => a.map((e, idx) => [e, b[idx]]);
const arr3 = flatten(zip(arr1, arr2));
console.log(arr3);
The answer is "kind of." What you can do is loop through one array with a forEach method, and use the optional argument index to get the value of the second array as well. Something like this:
var arr1 = [1,2,3,4,5];
var arr2 = ["a","b","c","d","e"];
arr1.forEach((value, index) => {
console.log(value);
console.log(arr2[index])
})
But if the data in the two arrays are at all related, you'd want to put the data in the same object, like this:
var arr = [
{
num: 1,
letter: "a"
},
{
num: 2,
letter: "b"
},
{
num: 3,
letter: "c"
}
];
arr.forEach(value => {
console.log(value.num);
console.log(value.letter);
})
Or you would want to use a regular for loop
You could simply use a for() loop instead:
const max = Math.max(arrA.length, arrB.length)
for (let i = 0; i < max; i++) {
const objA = arrA[i],
objB = arrB[i]
if ('undefined' !== typeof objA) {
console.log({ objA })
}
if ('undefined' !== typeof objB) {
console.log({ objB })
}
}
There is no real magic here. You use an index variable, and let it increment:
var arr1 = [1,2,3,4,5];
var arr2 = ["a","b","c","d","e"];
let ul = document.querySelector("ul");
for (let i = 0; i < arr1.length; i++) {
let li = document.createElement('li');
for (let val of [arr1[i], arr2[i]]) {
let span = document.createElement('span');
span.textContent = val;
li.appendChild(span);
}
ul.appendChild(li);
}
<ul></ul>
There are of course other ways to loop, like with forEach, but it comes down to the same principle.
BTW, don't use string literals (template literals) for combining HTML with content, as you might have < or & characters in the content, which really should be escaped. In some cases, not escaping those may lead to unexpected side effects. By creating the elements with createElement and assigning content to their textContent or innerText properties, you avoid those potential issues. Some libraries make it possible to do this with less code, in a more functional way.
As to the initial data: in object oriented languages, like JavaScript, it is better practice to put related values together in one object. In the example, 1 and "a" apparently have a connection, so -- if possible -- you should define the initial data structure as something like this:
var data = [
{ value: 1, name: "a" },
{ value: 2, name: "b" },
{ value: 3, name: "c" },
{ value: 4, name: "d" },
{ value: 5, name: "e" }
];

Issue with parsing the data into an integer JSON Array

I have a json file
{
"Val1":120,
"Val2":60,
"Val3":50
}
I need to pass those into two Global Arrays.
1st Array = ["Val1","Val2","Val3"]
2nd Array = [120,60,50]
You can use Object.keys & Object.values. Both of them will return array. Object.keys return array of keys and Object.values creates an array of values
let obj = {
"Val1": 120,
"Val2": 60,
"Val3": 50
}
let array1 = Object.keys(obj);
let array2 = Object.values(obj);
console.log(array1, array2)
You could use a for loop like the one here:
var jsonObject = {
"Val1":120,
"Val2":60,
"Val3":50
};
var arr1 = [];
var arr2 = [];
for(key in jsonObject) {
arr1.push(key);
arr2.push(jsonObject[key]);
}
console.log('Keys: ', arr1);
console.log('Values: ', arr2);

Javascript: Find a key with maximum value in a object after filtering keys based on an array

My js object:
data_obj = {'p1': 1, 'p2':2, 'p3':3}
my array
data_array = ['p1', 'p3']
Now, I want to filter the object based on the array. Expected result is
fil_obj = {'p1': 1, 'p3':3}
Now then, find the key having a maximum value. Expected result is
p3
Since I have object with thousands of items, I expect a very efficient solution.
Since I'm using d3js for this project, solution based on d3js like d3.max would be great.
You could iterate the wanted properties and return the max key.
var data_obj = { p1: 1, p2: 2, p3: 3},
data_array = ['p1', 'p3'],
result = data_array.reduce(function (r, a, i) {
return !i || data_obj[r] < data_obj[a] ? a : r;
}, undefined);
console.log(result);
I've never used d3, but it seems to me you can get the result pretty efficiently with a single call to .reduce():
var data_obj = {'p1': 1, 'p2':2, 'p3':3};
var data_array = ['p1', 'p3'];
var results = data_array.reduce((r,v)=>{
if (v in data_obj) {
r.data[v] = data_obj[v];
if (data_obj[v] > r.maxVal) {
r.maxKey = v;
r.maxVal = data_obj[v];
}
}
return r;
}, {data:{}, maxKey:null, maxVal:Number.NEGATIVE_INFINITY});
console.log(results);

Underscore.js: Replace item in collection

I've been using underscore.js for a week now and I really like it.
However, now I want to replace a single element in collection (vm.lists) with another element.
I tried doing the following:
_.each(vm.lists, function (el) {
if (el.id == list.id)
el = list;
});
and:
var l = _.findWhere(vm.lists, { id: list.id });
l = list;
But none of them changes the actual item in the collection. How would I do this properly?
You got pretty close. The issue is that you are only replacing the local variables (el and l) pointing to the value, and this does not modify the initial list. A simpler example:
var list = [1, 2, 3];
var v = list[1];
v = 7; // v will now point to a new value, but list will stay intact [1, 2, 3]
Same with objects:
var olist = [{id: 1, v: 2}, {id: 4, v: 6}];
var obj = olist[0];
obj = {id: 8, v: 10}; // changes what obj points to, but does not affect olist[0]
var obj2 = olist[0];
obj2.v = 777; // olist[0] still points to the same object but the object is modified
olist[0] = {id: 8, v: 10}; // changes what olist[0] points to
So basically you have two options:
a) change vm.lists[index] so that it points to a new object. You would need to get the index of the object in the list and do vm.lists[index] = newObject;. Note that some underscore predicates also provide you the index _.each(list, function (el, index) {});.
b) change the object that vm.lists[index] points to, but you would need to copy fields manually. For example, if your object is represented as {id: id, values: [1, 2, 3], anotherField: data}, you could copy the fields:
//el.id = list.id; // don't need this as you were searching by id
el.values = list.values;
el.anotherField = list.anotherField;
IMO the first option would be cleaner.
there is no need for underscore here:
for (var i = 0, l = vm.lists.length; i < l; i++)
{
var el = vm.lists[i];
if (el.id == list.id) {
vm.lists[i] = list;
break; // stop the for loop
}
}

Push data into JavaScript object

I have the following JavaScript object -
var newArray = { "set1": [], "set2": [] };
I am trying to push new data in this like -
newArray.set1.push(newSet1);
newArray.set2.push(newSet2);
Where newSet1 and newSet2 is equal to -
[{"test1","test1"},{"test2","test2"}] & [{"test3","test3"},{"test4","test4"}]
However when this is getting pushed in it is creating additional square brackets with the end result looking like -
{ "set1": [[{"test1","test1"},{"test2","test2"}]], "set2": [[{"test3","test3"},{"test4","test4"}]] }
When I actually need -
{ "set1": [{"test1","test1"},{"test2","test2"}], "set2": [{"test3","test3"},{"test4","test4"}] }
I tried setting my newArray as blank like -
var newArray = { "set1": '', "set2": '' };
However this did not work. How can I adjust it to accept the sets without adding additional brackets?
Use .concat()
var newArray = { "set1": [], "set2": [] };
newArray.set1 = newArray.set1.concat(newSet1);
newArray.set2 = newArray.set2.concat(newSet2);
You should say
newArray.set1.push(newSet1[0]);
newArray.set1.push(newSet1[1]);
newArray.set2.push(newSet2[0]);
newArray.set2.push(newSet2[1]);
newArray.set1 = newSet1;
newArray.set2 = newSet2;
Use Like
var newArray = { "set1": [], "set2": [] };
var arr1 = new Array ("A", "B", "C");
var arr2 = new Array (1, 2, 3);
var multiArr = new Array (arr1, arr2);
// or
var multiArr = [arr1, arr2];
// or
var multiArr = [["A", "B", "C"], [1, 2, 3]];
// you can access the elements of the array by zero-based indices
var firstRow = multiArr[0]; // same as arr1
var secondRowFirstCell = multiArr[1][0]; // 1
newArray.set1.push(multiArr[0]); //so, you need to use this with
newArray.set1.push(multiArr[1]); //so, you need to use this with
console.log(newArray);
DEMO

Categories

Resources