Failing accessing array which is property of an object in Javascript - javascript

I'm trying to access array which is property of an object, but I can only access letters from property name.
var obj = {};
obj.line0=[0,0];
obj.line1=[0,50];
var pointsLenght = 8;
//things above are just test case sandbox representing small amount of real data
var createPoints = function(obj){
var i;
for(var x in obj){
if (obj.hasOwnProperty(x)) {
for (i=0;i<pointsLenght;i++){
if (i%2==0){
x[i]=i*50;
}
else {
x[i]=x[1];
}
console.log(i+" element of array "+x+" is equal "+x[i]);
}
}
}
return obj;
}
And this is what I get in console (Firefox 47.0):
0 element of array line0 is equal l
1 element of array line0 is equal i
2 element of array line0 is equal n
3 element of array line0 is equal e
4 element of array line0 is equal 0
5 element of array line0 is equal undefined
6 element of array line0 is equal undefined
7 element of array line0 is equal undefined
How to access array?

You are accessing the property name, that is a string. ("line0" and "line1")
For accessing the array belongs to that property name, Just write your code like,
var createPoints = function(obj){
var i;
for(var x in obj){
if (obj.hasOwnProperty(x)) {
for (i=0;i<pointsLenght;i++){
if (i%2==0){
obj[x][i]=i*50;
//obj[x] will give you the array belongs to the property x
}
else {
obj[x][i]= obj[x][1];
//obj[x] will give you the array belongs to the property x
}
console.log(i+" element of array "+x+" is equal "+ obj[x][i]);
}
}
}
return obj;
}

Operations need to be done obj[x].
Please Check with the code:
var obj = {};
obj.line0 = [0, 0];
obj.line1 = [0, 50];
var pointsLenght = 8;
//things above are just test case sandbox representing small amount of real data
var createPoints = function(obj) {
var i, elem;
for (var x in obj) {
if (obj.hasOwnProperty(x)) {
elem = obj[x];
for (i = 0; i < pointsLenght; i++) {
elem[i] = (i % 2 == 0) ? (i * 50) : elem[1];
console.log(i + " element of array " + elem + " is equal " + elem[i]);
}
}
}
return obj;
}
createPoints(obj);

Related

Get highest index key of Javascript array

How can I get the highest key in an array like that:
foo[0] == undefined
foo[1] == "bar"
foo[2] == undefined
foo[3] == undefined
foo[4] == "bar"
foo.length returns me 2, so if i iterate foo.length times, I'll never get the last value.
Or is there a way to count an array considering the undefined values as well?
I am unsure why your code is not working, .length on an array like that shows 5 correctly in my example here
However, if you do not set values at all on specific indexes, you can do this :
var foo = [];
foo[1] = "bar";
foo[4] = "bar";
//grab existing indexes that have values assigned
var indexes = foo.map(function(val, idx) { return idx; });
//get the last one, this + 1 is your real length
var realLength = indexes[indexes.length - 1] + 1;
console.log("Real length: ", realLength);
//iterate using for loop
for(var i=0; i<realLength; i++) {
var val = foo[i];
console.log(i, val);
}
Highest Key
var index = foo.lastIndexOf(foo.slice(-1)[0]);

How to get the property with the largest number?

I need to return a new object from an original object.
The original object's property values are numbers bigger than 0, and I want to return the property with the largest value.
Edit: I want to return the largest property only if the property's $.isNumeric() is true; Apologies for my poor English.
obj = {2:1, 3:4, a:8, 5:2, 4:5 }; //expected newobj = {5:5};
Largest number in an array of strings (ignoring non-numeric):
function maxInArr(arr) {
return Math.max.apply(void 0, arr.filter($.isNumeric).map(Number));
}
Largest property:
var maxProp = maxInArr(Object.keys(obj));
Largest value:
var maxVal = maxInArr(Object.keys(obj).map(function(p){
return obj[p];
}));
Build the object:
var obj2 = {};
obj2[maxProp] = maxVal;
obj2; // {5: 8}
Try putting your array into this simple function:
function heighest(yourArray) {
var keys = Object.keys(yourArray);
var values = Object.keys(yourArray);
for (int i = 0; i < keys.length; i++)
{
keys[i] = parseInt(keys[i]);
values[i] = parseInt(values[i]);
}
var highestKey = Math.max.apply(Math, keys);
alert('Heighest key: ' + highestKey + ', with value ' + yourArray[highestKey]);
};
If I understood question correctly this should be possible answer.
var obj = {2:1, 3:4, a:8, 5:2, 3:5, 3:5};
var max = Number.MIN_VALUE;
for(var propertyName in obj) {
if(!isNaN(propertyName) && propertyName > 0){
if(obj.hasOwnProperty(propertyName) && obj[propertyName] > max){
max = obj[propertyName];
}
}
}
console.log(max);
Here is jsfiddle: http://jsfiddle.net/4bLe9jbj/1/

Returning variable name from array?

Is it possible to return a variable name from an array?
I have an array with 5 variables. Each variable is assigned a numeric value.
I am trying to find the highest value in the array and then alert its variable name, or possibly use that variable to do things with it.
var vara = 0; //resultA
var varb= 0; //resultB
var varc= 0; //resultC
var vard= 0; //resultD
var vare= 0; //resultE
function showResults() {
var buckets = [vara, varb, varc, vard, vare];
var largest = Math.max.apply(Math, buckets);
alert(largest);
}
The above code alerts the value of largest, but I want to find the corresponding variable, for instance vara instead of 3
No, it is not. If you want to associate some name with value, thats what dictionaries for.
var obj = {"name": 123, "name2": 234}
obj.name3 = 345; // assign 345 to name3
var valueOfName3 = obj.name3; // get name3
If you want to get the largest value in this object (by akonsu):
var largest = null;
var keyOfLargestVal = null;
for(var k in obj) { var v = obj[k];
if (largest === null || v > largest){
largest = v; keyOfLargestVal = k;
}
}

Are there such things as dynamic-dimensional arrays in JavaScript?

What I mean by dynamic-dimensional arrays is multidimensional arrays that can have various dimensions. I need to create a function that does something to elements of multidimensional arrays, regardless of their dimensions. I wrote a function that should loop through all elements of a multidimensional array, but I can't find a way to get them. Here's what I wrote:
function loopThrough (multiArray, dimensions) {
var i, indexes = new Array(dimensions.length);
// stores the current position in multiArray as index combination
for (i in indexes) indexes[i] = 0; // position is initialised with [0, 0, ... 0]
while (i >= 0) {
doStuff(multiArray[indexes[0], indexes[1], ... indexes[?]]); // this is where I got stuck
for (i = indexes.length - 1; i >= 0 && ++indexes[i] >= dimensions[i]; indexes[i--] = 0);
// creates the next index combination
}
}
I also need a way to create such arrays. Say in an object's constructor, like:
function MultiArray (dimensions) {
this.array = [];
// create multidimensional array
}
For example, if I want to create a 5x3x8 array I should be able to call MultiArray([5,3,8]); just the same as calling MultiArray([4,6]); for a 4x6 array, or MultiArray([7]); for a plain 7-lengthed array.
You can use something like this:
function MultiArray(dimensions) {
var a = [];
if (dimensions > 1) {
a.push(MultiArray(dimensions -1));
}
return a;
}
var m = MultiArray(4);
function MultiArray(dimensions) {
this.elements = [];
var leaf = dimensions.length == 1;
var dimension = dimensions.shift();
for (var i = 0; i < dimension; ++i) {
this.elements.push(leaf ? undefined : new MultiArray(dimensions));
}
}
MultiArray.prototype.get(indexes) {
var leaf = indexes.length == 1;
var index = indexes.shift();
return leaf ? this.elements[index] : this.elements[index].get(indexes);
}
MultiArray.prototype.set(indexes, value) {
var leaf = indexes.length == 1;
var index = indexes.shift();
if (leaf) {
this.elements[index] = value;
} else {
this.elements[index].set(indexes, value);
}
return this;
}
var m = new MultiArray([4, 3, 5]);
m.set([1, 2, 4], "i'm a value in a multi dimensional array");
m.get([1, 2, 4]); // should return "i'm a value in a multi dimensional array"
m.get([2, 0, 3]); // should return undefined
m.get([0, 1]); // should return an array of 5 elements

Display number if each item in JavaScript array

I am trying to display the contents of an array in a more readable way, this is the array:
["malevolent", "pariah", "judicious", "pariah", "judicious"]
I'm simply adding that array to an HTML element to display it, but I want to display it like this:
malevolent, pariah x 2, judicious x2
How would I do this?
It's quite simple actually:
var myArray = new Array("a", "b", "c", "b", "a");
var newObject = {};
// Iterate over the array
for(var i = 0; i < myArray.length; i++){
// If the new object already contains the key (e.g. a, b, or c), increment value by one
if(myArray[i] in newObject){
newObject[myArray[i]]++;
} else {
// Otherwise add a key (e.g. a, b, or c) to the object and assign 1 to it (first occurence)
newObject[myArray[i]] = 1;
}
}
// Write the resulting object to console
window.console && console.log(newObject);
newObject contains a list of keys (a,b,c) and values (number of occurrences of each key). You can than use that data to output it in any format you like, but that's left up to you as an excercise.
You can try the following:
var myArray = ["malevolent", "pariah", "judicious", "pariah", "judicious"];
var resultArray = [];
var countArray = [];
for(index in myArray) {
var element = myArray[index];
var isInArray = resultArray.indexOf(element);
if(isInArray !== -1) {
var tmpCnt = countArray[isInArray];
tmpCnt++;
countArray[isInArray] = tmpCnt;
} else {
resultArray.push(element);
countArray.push(1);
}
}
console.log(resultArray);
console.log(countArray);
Felix Kling provided a Link to an answer on how to count your elements. I just shamelessly use the reduce method described there and then just iterate over the object to build a string.
var a = ["malevolent", "pariah", "judicious", "pariah", "judicious"].reduce(function (acc, curr) {
if (typeof acc[curr] == 'undefined') {
acc[curr] = 1;
} else {
acc[curr] += 1;
}
return acc;
}, {});
var out = "";
for (var k in a) {
out += k + " x " + a[k] + "; ";
}
console.log(out);
try this
var arr = new Array("malevolent", "pariah", "judicious", "pariah", "judicious");
var new_arr1 = new Array(); // for containing distinct values like pariah
var new_arr2 = new Array(); // for containing distinct values count like 2 for pariah
// both will be on same index in new_arr1 and new_arr2
for(var i=0; i<arr.length; i++)
{
// fetch every value of arr
var indx = $.inArray(arr[i], new_arr1); // check value is exists in new_arr1 and get index
if(indx > -1) // values exists in new_arr1
{
var v = new_arr2[indx]+1; // increment the previous count +1
new_arr2[indx] = v; // update it on the index of new_arr2
}
else
{
// if value not in new_arr1 means the value comes first time
var l = new_arr1.length;
new_arr1[l] = arr[i]; // insert value in new_arr1
new_arr2[l] = 1; // initate count 1 for the same index of new value in new_arr2
}
}
// now new_arr1 will contains the distinct values
// and new_arr2 contains the count for distinct values
// eg new_arr1[0] = 'malevolent';
// new_arr2[0] = 1;
// new_arr1[1] = 'pariah';
// new_arr2[1] = 2;
// now you can fetch distinct values and their count like given below
for(var i=0; i<new_arr1.length; i++)
{
var str = new_arr1[i]+" X "+new_arr2[i];
alert(str);
}
See FIDDLE

Categories

Resources