when i do console.log(myArray) I obtain this:
console.log result
I want to take a value inside only one of this arrays, but how? When i do console.log(array[0]) I obtain this result:
37.7
28.45
36.38
You have nested arrays. So your main array has three elements each of which contains one number, and the indexes of those arrays go from 0 to 2.
You access each nested array with its index, and then access the number with the 0 index (because there's only one element in that nested array).
const arr = [[37.7], [28.45], [36.38]];
console.log(arr[0][0]);
console.log(arr[1][0]);
console.log(arr[2][0]);
Or even loop over the array and destructure the number from each nested array:
const arr = [[37.7], [28.45], [36.38]];
for (let [number] of arr) {
console.log(number);
}
From what I can see in the original question so far, the output of this function is actually three different console.log() executions, which leads me to believe that whatever is firing these console.logs is actually running in some sort of loop.
If that is the case, you will not be able to pull just one value out to simply. The screenshot you added only shows the output. Could you please add the code for (or screenshot of) all the related code from setting up or fetching the array, to your console.log? With all that context, I can rewrite my answer to get you the exact answer you are looking for.
Please compare your code with this working example:
let myArray = [37.7, 28.45, 36.38];
console.log(myArray[0]); // outputs 37.7
Related
I'm trying to setup a 2-d array, which should receive values at specific sub-arrays. I created my array with:
myArray= Array(100).fill([])
Now, let's say I want to push a value to say sub-array number 40
I'm doing this like that:
myArray[40].push("myValue")
I would expect the value to be pushed only to the myArray[40] instead it is pushed as the first element of every of the hundred sub-arrays.
I searched for the solution for quite some time, but I still have no idea what I'm doing wrong. Please help.
fill will push the same value to each element, not a copy of it. That's fine when it's a number or string or something else immutable. But now each copy is a reference to the same object.
There are a number of ways to fix this. Here's one (switched to ten elements for demonstration):
const myArray = [...Array(10)].map((_, i) => [])
myArray[4].push('myValue')
console.log(myArray)
Why does it say length 1 instead of 4?
The following is what I'm trying to push and slice. I try and append items.image_urls and slice them into 5 each.
items.image_urls is my dictionary array.
var final_push = []
final_push.push(items.image_urls.splice(0,5))
console.log(final_push.length)## gives me 1...?
var index = 0
final_push.forEach(function(results){
index++ ##this gives me one. I would need 1,2,3,4,5,1,2,3,4,5. Somehting along that.
}
items.image_urls looks like this:
It's an iteration of arrays with image urls.
In your example items.image_urls.splice(0,5) returns an array of items removed from items.image_urls. When you call final_push.push(items.image_urls.splice(0,5));, this whole array is pushed as one item to the final_push array, so it now looks like [["url1", "url2", "url3", "url4", "url5"]] (2-dimensional array). You can access this whole array by calling final_push[some_index].
But what you want instead is to add every element of items.image_urls.splice(0,5) to the final_push. You can use a spread operator to achieve this:
final_push.push(...items.image_urls.splice(0,5));
Spread syntax allows an iterable such as an array expression or string
to be expanded in places where zero or more arguments (for function
calls) or elements (for array literals) are expected
This is exactly our case, because push() expects one or more arguments:
arr.push(element1[, ...[, elementN]])
And here is an example:
let items = {
image_urls: ["url1", "url2", "url3", "url4", "url5", "url6", "url7", "url8", "url9", "url10"]
};
let final_push = [];
final_push.push(...items.image_urls.splice(0,5));
console.log(final_push.length);
console.log(JSON.stringify(final_push));
console.log(JSON.stringify(items.image_urls));
Note: do not confuse Array.prototype.slice() with Array.prototype.splice() - the first one returns a shallow copy of a portion of an array into a new array object while the second changes the contents of an array by removing existing elements and/or adding new elements and returns an array containing the deleted elements.
That seems to be a nested array. So if you would access index 0, and then work on that array like below it will probably work:
console.log(final_push[0].length); //should print 4
The author is mixing up splice and slice. Probably a typo :)
You start at the beginning (0) and then delete 5 items.
I'm working with a web framework and I'm using variables from Python into Javascript code.
I get next array in Python, which can contain more than one cell with dictionaries inside it:
[[{'lacp_use-same-system-mac': u'no'}, {'lacp_mode': u'passive'}, {'lacp_transmission-rate': u'slow'}, {'lacp_enable': u'no'}]]
I want to be able to access every cell array and, after that, get every keys from the dictionary inside this cell array. Up to now, I only have arrays or dictionaries, so for both cases I did next:
var X = JSON.parse(("{{X|decodeUnicodeObject|safe}}").replace(/L,/g, ",").replace(/L}/g, "}").replace(/'/g, "\""));
Where X is the Python variable. Unfortunately, this does not run with the array I wrote above.
How can I do that?
Thanks beforehand,
Regards.
I want to be able to access every cell array and, after that, get
every keys from the dictionary inside this cell array
If I understood correctly you want to get the keys of a nested array.
Note: your array isn't valid js.
const arrarr = [[{key1: 'val1'}, {key2: 'val2'}], [{key3: 'val3'}, {key4: 'val4'}]];
arrarr.forEach(arr => {
arr.forEach(e => {
Object.keys(e).forEach(k => console.log(k))
})
})
If the depth of nests is of arbitrary depth you can use recursion and check if the child is an array, if it is keep going, else get the keys.
I have a scenario, where I have two different Objects.
Scenario to achieve:
From two objects I need to match the values which has "A1","B2", etc...
Since both the objects values are not in proper order, the loop is breaking and missing some values.
In my demo the object1 has same repeated value i.e. "C3", It should be displayed only once.
Final output required is I need to detect only the matched values from two objects and display its corresponding "a" and "b values."
I have tried almost 90%, but somewhere some minor error is breaking my loop, Please help me out.
Sample code:
for(var i=0;i<obj1.results[0].loc.length;i++){
var findA = obj1.results[0].loc[i].anc[0].title;
for(var j=0;j< obj2.ILoc.length;j++){
var findB = obj2.ILoc[j].ais;
if(findA == findB) {
var a = obj1.results[0].loc[i].a;
var b = obj1.results[0].loc[i].b;
console.log(a);
console.log(b);
}
}
}
This is what I have tried:
Demo Link
I would recommend using for...in loop, since you're using objects instead of arrays.
for (variable in object) {...
}
If length property of both objects is equal, then this kind of loop alone will help you to compare objects with ease.
I would recommend using the diff module. You can use it in node.js and the browser.
I am having trouble understanding how to call specific array values:
I have commented out the questions in the code. Please take a look and let me know why the array produces one result within the function, while producing a different result outside of it. To run the code, please use a website like repl.it
var passengers = [ ["Thomas", "Meeks"],
["Gregg", "Pollack"],
["Christine", "Wong"],
["Dan", "McGaw"] ];
var results = passengers.map(function (array) {
// The following prints out the first names--the entire first column. Why?
console.log(array[0]);
});
console.log(); // Just empty space
// Why is the following only printin the first row of passengers (which it should), but the array[0] printed out the entirety of the first column?
console.log(passengers[0]);
You have an array of arrays, so when you call map here:
var results = passengers.map(function (array) {
// The following prints out the first names--the entire first column. Why?
console.log(array[0]);
});
It's looping through the outer array. The parameter that gets passed into the function is the element of the array that you're looping through, in this case, the inner array. So the console.log(array[0]) is printing the first element of the inner array.
In other words, this code is roughly equivalent to:
console.log(passengers[0][0]);
console.log(passengers[1][0]);
console.log(passengers[2][0]);
console.log(passengers[3][0]);
Notice that in this example, I'm only iterating through the outer array (the first index). The inner array index stays at zero.
But later where you have
console.log(passengers[0]);
It's simply printing the first element from the outer array, which is the entire first inner array.
Further Reading
Array
Array.prototype.map()