javascript array set deep value - javascript

I have an array called insurances. I set data in this array like this:
var insurances = {};
insurances[0] = {}
insurances[0]['id'] = 0;
etc...
Later on i want to change the id by doing this:
insurances[index]['id'] = insuranceId;
The index = 0 and the insuranceId = 1000;
Somehow it doesn't set the value (i get undefined). What am i doing wrong?
Thanks for helping.

It works: http://jsfiddle.net/pNAwk/
var insurances = {};
insurances[0] = {}
insurances[0]['id'] = 0;
insurances[0]['id'] = 1000;
alert( insurances[0]['id'] ); // alerts 1000
Note that if you intend to use indexed property names (0, 1, 2, ...), then an array literal is more appropriate:
var insurances = [];

Related

Remove Duplicate elements from Array - Javascript (No JQuery & ECMAScript)

Case: We have 'n' number of arrays stored in an array (Array of Arrays). Now that each child array in this parent array can have elements that may or may not be present in other child arrays. Output - I need to create an array which has the all the elements present in all the child arrays excluding the duplicates.
I do not want to concatenate all the arrays into a single array and use unique method to filter out. I need to create unique array then and there during iteration.
Ex:
var a[] = [1,2,3,4,5];
var b[] = [1,2,7,8];
var c[] = [1,2,3,4,5,6,7,8];
var d[] = [9,10,11,12];
var arr[] = [a,b,c,d]
Output must be [1,2,3,4,5,6,7,8,9,10,11,12]
P.S: I can concat the arrays and use jquery unique function to resolve this, but i need a solution in javascript alone. Thanks
You can use array#reduce to flatten your array and then use Set to get distinct values and use array#from to get back array from Set.
var a = [1,2,3,4,5];
var b = [1,2,7,8];
var c = [1,2,3,4,5,6,7,8];
var d = [9,10,11,12];
var arr = [a,b,c,d]
var result = Array.from(new Set(arr.reduce((r,a) => r.concat(a))));
console.log(result);
Try using .filter when adding each array to the final one, filtering out the duplicates:
a.filter(function(item) {
return !finalArray.contains(item));
});
Answer using Sets:
var a = [1,2,3,4,5];
var b = [1,2,7,8];
var c = [1,2,3,4,5,6,7,8];
var d = [9,10,11,12];
var concat = a.concat(b).concat(c).concat(d);
var union = new Set(concat);
//console.log(union);
ES6 Answer:
let a = new Set([1,2,3,4,5]);
let b = new Set([1,2,7,8]);
let c = new Set([1,2,3,4,5,6,7,8]);
let d = new Set([9,10,11,12]);
let arr = new Set([...a,...b,...c,...d]);
//Result in arr.
Whats going on???
From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set:
The Set object lets you store unique values of any type, whether
primitive values or object references.
So when we initialise Sets passing arrays to the constructor we basically ensure that there are no duplicate values.
Then in the last line, we concat all the Sets we initialised prior into a final set.
The ... notation converts the Set into an array, and when we pass the 4 arrays to the constructor of the Set they get concatenated and a Set of their unique values is created.
Here is a functional alternative written in ES5.
var flatten = function(list) {
return list.reduce(function(acc, next) {
return acc.concat(Array.isArray(next) ? flatten(next) : next);
}, []);
};
var unique = function(list) {
return list.filter(function(element, index) {
return list.indexOf(element) === index;
})
}
var a = [1,2,3,4,5];
var b = [1,2,7,8];
var c = [1,2,3,4,5,6,7,8];
var d = [9,10,11,12];
var arr = [a,b,c,d];
var result = unique(flatten(arr));
console.log(result);
If you support ES6, arrow function can make that code even shorter.
Here is a solution that uses a plain object for resolving duplicates, and only uses basic ES3 JavaScript. Runs in IE 5.5 and higher, and with O(n) time complexity.
function uniques(arr) {
var obj = {}, result = [];
for (var i = 0; i < arr.length; i++) {
obj[arr[i]] = true;
}
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) result.push(+prop);
}
return result;
}
// Example use
var a = [1,2,3,4,5],
b = [1,2,7,8],
c = [1,2,3,4,5,6,7,8],
d = [9,10,11,12];
var result = uniques(a.concat(b, c, d));
console.log('Result: ' + result);
As an object can only have a unique set of properties (no duplicates), the use of all array values as properties in an object will give you an object with a property for each unique value. This happens in the first loop. NB: the value given to those properties is not relevant; I have used true.
Then the result is just the conversion of those properties back to array values. This happens in the second loop.
var a = [1,2,3,4,5];
var b = [1,2,7,8];
var c = [1,2,3,4,5,6,7,8];
var d = [9,10,11,12];
var result = a.concat(b,c,d);
function remvDup(result){
var tmp = [];
for(var i = 0; i < result.length; i++){
if(tmp.indexOf(result[i]) == -1){
tmp.push(result[i]);
}
}
return tmp;
}
console.log(remvDup(result));
Becuase the OP mentioned that he cannot use 'Set' as it is not supported on the targeted browsers, I would recommand using the 'union' function from the lodash library.
See union's documentation here

set jquery multidimensional array

I'm getting attribute values. I need to set into multidimensional array but it's showing error. where im getting wrong ?
var myArray = [];
amount=10;
x=1
$(id).closest('td').nextAll().find('input').each(function (n) {
myArray[x]['id'] = $(this).attr('data-id');
myArray[x]['year'] = $(this).attr('data-year');
myArray[x]['month'] = $(this).attr('data-month');
myArray[x]['amount'] = amount;
x++;
});
console.log(myArray);
you are missing this line
myArray[x] = {};
before this line
myArray[x]['id'] = $(this).attr('data-id');
since you need to initialize this object first before setting properties to it.
Arrays need to be declared first to add items. For example
var d = [];
var value = 2;
d[0]["key"] = value;
won't work because d[0] is not an array yet. But:
var d = [];
var value = 2;
d[0]= [];
d[0]["key"] = value;
will work, because d[0] is ready to accept keys.
In your case;
>>> myArray[x] = [];
myArray[x]['id'] = $(this).attr('data-id');
myArray[x]['year'] = $(this).attr('data-year');
myArray[x]['month'] = $(this).attr('data-month');
myArray[x]['amount'] = amount;
will work.
Even though, you have initialized the array as an empty array, you should initialize the values at a paritcular location. when you dont specify, myArray[x] is undefined. So, you need to explicitly assign an empty object , so as to update keys using myArray[x]["key"]
var myArray = [];
amount = 10;
x = 1
$(id).closest('td').nextAll().find('input').each(function(n) {
//Need to initialize with an object a location x;
myArray[x] = {};
myArray[x]['id'] = $(this).attr('data-id');
myArray[x]['year'] = $(this).attr('data-year');
myArray[x]['month'] = $(this).attr('data-month');
myArray[x]['amount'] = amount;
x++;
});
console.log(myArray);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

How do I define an associative array?

I want to define what I understand is an associative array (or maybe an object) such that I have entries like the following:
"Bath" = [1,2,5,5,13,21]
"London" = [4,7,13,25]
I've tried the following:
var xref = new Object;
xref = [];
obj3 = {
offices: []
};
xref.push(obj3);
Then cycling through my data with
xref[name].offices.push(number);
But I get "TypeError: xref[name] is undefined". What am I doing wrong ?
Use an object like you do with obj3:
var xref = {};
xref.obj3 = obj3;
var name = 'obj3';
xref[name].offices.push(number);
var obj = {
arr : [],
}
var name = "vinoth";
obj.arr.push(name);
console.log(obj.arr.length);
console.log(obj.arr[0]);
obj.prop = "Vijay";
console.log(obj.prop);
You can use an object literal.
I realised that all I really wanted was a 2 dimensional array with the first dimension being the key (ie. "BATH", "LONDON") and the second being the list of cross-references (ie. 1,2,5,5,13,21) - so I don't need to understand the Object route yet ! The other suggestions may well work and be "purer" but the 2 dimensional array is easier for my old-fashioned brain to work with.
So I did the following:
var xref = [];
// go through source arrays
for (i = 0; i < offices.length; i++) {
for (j = 0; j < offices[i].rel.length; j++) {
// Check if town already exists, if not create array, then push index
if (xref[offices[i].rel[j].town] === undefined) {
xref[offices[i].rel[j].town] = [];
alert('undefined so created '+offices[i].rel[j].town);
};
xref[offices[i].rel[j].town].push(i); // Add index to town list
};
};
I believe from reading other posts that I would have problems if any of the 'offices[i].rel[j].town' were set to undefined but the data doesn't have this possibility.
Now I can access a cross-reference list by doing something like:
townlist = "";
for (i = 0; i < xref["BATH"].length; i++) {
townlist += offices[xref["BATH"][i]].name+' ';
};
alert(townlist);

need help javascript array = [] and how to output name of variable in array with value

I have a question about array as below
array = {}
and
array = [];
its same or not?.
also wish to ask
array { ID1 : "apple", ID2 : "Orange"}
and
array [ID1 : "apple", ID2 : "Orange"];
which is correct?.
now i coding my code with below and need your help to teach me about ARRAY.
var Store = [ store = 0, store1 = 0, store2 = 0,store3 = 0,store4 = 0];
var stock1 = 77,stock2 = 47,stock3 = 37,stock4 = 27,stock5 = 17;
for(i=0;i<stock1;i++){
store[0]++
}
var Sum_1 = Store;
document.getElementById('show1').innerHTML=Sum_1;
output will be
77
my question is how to i output it become
store = 77
store1 = 47
store2 = 37
Most with ID or Name together and value.
Thank you so much.
[] are used for a literal Array declaration, {} for a literal Object declaration.
Arrays are initialized without a value by using:
var my_array = [];
and with values:
var my_array = [1, 2, 3];
Note that you cannot set the index by this. You would have to do:
var my_array = [];
my_array["one"] = 1;
// etc.
You can then get "1" back by my_array["one"]
If you want to get the actual index name or "key" then you will need to do some trickery:
var outputString = "";
function ListAll()
{
for(var key in my_array)
{
if(my_array.hasOwnProperty(key)) // Check if the key is actually a property (index)
{
outputString += key + " = " + my_array[key]; // add to string
}
}
alert(outputString); // or assign the string to a div, whatever you need
}
in this example, key would be the index and my_array[key] the actual value

How do I convert this object to an array in JavaScript?

How do I convert testObj to an array?
function MinEvent(event, width, left){
this.start = event.start;
this.end = event.end;
this.width = width;
this.top = event.start;
this.left = left;
}
var testObj = {};
for (var j=0; j<eventLists.length; j++) {
var eve = eventLists[j];
var event = new MinEvent(eventList[j], width, left);
testObj[eve.id] = event;
}
Technically every object in javascript can be treated like an array. Your code should work as-is.
But either way, looking at your code, why not define testObj as var testObj = [];?
If you declare testObj as an array initially you don't need to convert it.
//declare the array
var testObj = new Array();
or
//declare the array
var testObj = [];
Index based access should work for either of these. I.e.
testObj[0] = "someval";
etc.
I'm not sure why you'd want to do that. JavaScript objects are actually the same as an associative array already. You could access all of its properties and methods like this:
for(prop in obj) {
alert(prop + ” value : ”+ obj[prop];
}
Maybe it would help if you told us what you wanted to do once you converted the object inot an array (and what you want the result to look like).
var array = []
for( var prop in testObj )
{
array.push( testObj[prop] );
}
Is this what you want?

Categories