set jquery multidimensional array - javascript

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>

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

Convert javascript object keys to real int after JSON encoded

I have this:
var a = {};
a[1] = 1;
a[4] = 4;
console.log(JSON.stringify(a));
then I get:
{"1":1,"4":4}
but I want to get:
{1:1,4:4}
how to reach this? In other words, I want to keys be real int.
When you call JSON.stringify() method it creates a valid JSON string.
One of the rules for valid JSON is that every property should be in "quotes".
So thats why it is impossible to get such result as you want using JSON.stringify.
If you want to just convert such object to array it is possible, for example usin such function.
function numerableObjectToArr(obj) {
var result = [];
var keys = Object.keys(obj);
keys.forEach(function(item){
result.push(obj[item]);
})
return result;
}
var a = {};
a[1] = 1;
a[4] = 4;
numerableObjectToArr(a); // returns [1, 4]
But in this way you will just receive Array with values of existing properties in the obj.
But if your prop name means the index in the array, and you are sure that there will be always number as a prop name - you can improve this function:
function numerableObjectToArr(obj) {
var result = [];
var keys = Object.keys(obj);
keys.forEach(function(item){
result[+item] = obj[item]; //we put index, then we put value to that place in array
})
return result;
}
var a = {};
a[1] = 1;
a[4] = 4;
numerableObjectToArr(a); // returns [undefined, 1, undefined, undefined, 4]
I'm not sure you can do what you're trying to do the as the keys have to be string values. I'd advise having string name for your keys (i.e 1 = One, 2 = Two, etc). You could then try this:
var a = {};
a.one = 1;
a.two = 2;
a.three = 3;
a.four = 4;
console.log(JSON.stringify(a));
I hope this helps.
var a = {};
a[1] = 1;
a[4] = 4;
alert(JSON.stringify(a).replace(/\"([0-9]+)\":/g, '$1:'));
But it is kludge. JSON - has a string keys.

Js: multidimensional array literal declared: Add elements

I wanted to know if its possible to ad elements to an array which is declared as the following...
Please check the add() function, I can't figure out how to solve this problem. Thanks
It's not necessary, but I'd appreciate if you give an explanation since of c++ point of view programmer.
// My array is this way declared
var myArray = [
['John', 'Doe', '1980'],
['Jane','Malloy','1982'],
['Vincent','Malloy','1972']
];
// then I want to add a new elements in it, but It seems to doesn't work
var add = function() {
//var textbox = document.getElementById('textbox').value;
// storing new person in array
myArray [3][0] = 'New1';
myArray [3][1] = 'New2';
myArray [3][2] = 'New3';
};
//finally this function is for displaying the elements of myArray
var show = function() {
// clean output
document.getElementById('output').innerHTML = '';
// delay time
setTimeout (function() {
// showing info. people
for (var i in myArray) {
for (var j in myArray)
document.getElementById('output').innerHTML += myArray[i][j] + ' ';
document.getElementById('output').innerHTML += '<br/>';
}
}, 250);
};
So right here:
var add = function() {
//var textbox = document.getElementById('textbox').value;
// storing new person in array
myArray [3][0] = 'New1';
myArray [3][1] = 'New2';
myArray [3][2] = 'New3';
};
You can't add to myArray[3] because myArray[3] is undefined. You need to assign an empty array to myArray[3] first:
myArray [3] = [];
myArray [3][0] = 'New1';
myArray [3][1] = 'New2';
myArray [3][2] = 'New3';
Or more generally, assuming the idea is to add to the end of your array, you could do something like:
var idx = myArray.length;
myArray[idx] = [];
myArray[idx][0] = "New 1";
// ...
Or even something like:
var newArray = ["New1", "New2", "New3"];
myArray.push(newArray);

Handling of array; returned by methods in iOS UI Automation

I have been able to use all the methods for automating iphone app test except with ones which returns array... e.g elements()
I have tried to do it using declaration of array as
var arr = [];
var arr = UIATarget.localTarget().frontMostApp().mainWindow().tabBar().elements();
UIALogger.logPass("result"+ arr[0]) // just to get first element
But it is not working
Can someone ans how to handle array. What is the correcting required?
What exactly do you want from such array?
Here is an example how to handle array of elements:
function getAllNamesInList (list, index){
var elem_list = list[index].elements();
var elem_count = elem_list .length;
var names = [];
var elem_name;
for (var elem_ind = 0; elem_ind < elem_count ; elem_ind++){
elem_name= elem_list [cell_ind].name();
if (!elem_name){fail ("TEST_INFO: Empty Element name!!!");}
names.push(elem_name);
}
return names;
};
Here is usage example of this function():
Your case:
var app = UIATarget.localTarget().frontMostApp();
var window = app.mainWindow();
var arr = window.tabBar()
var current_names = [];
current_names = getAllNamesInList (arr , 0);
UIALogger.logMessage ("Here are ALL names from array " + current_names );
Other possible lists which can be transferred and used within this function():
var table_views = window.tableViews();
var tab_bar = app.tabBar();
var nav_bar = app.navigationBar();

javascript array set deep value

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

Categories