Get value from javascript nested array - javascript

I am new in coding JavaScript. So far I know how to set and get values from a multi array, but with this one I cannot find the right way to do it.
I am trying to get the email value from this array:
__arr.push(['id' ,'12541']);
__arr.push(['tag', {"sub":false,"email":"email#email.com"}]);
I tried
JSON.parse(__ar.tag.email)
document.write(__ar[2][2])
Everything I tried so far I got either undefined or tag[object, object].
What's the easiest way to get it?

The email property is located on the second element of the array (that is index 1 of the zero based indexed array). So, to access it, you also need to access the second object of the element (again index 1) and then .email is at your hand:
document.write(__arr[1][1].email);

Assuming that you only push those two values, your array looks like the following:
[
['id' ,'12541'],
['tag', {"sub":false,"email":"email#email.com"}]
]
Means, that when you access it using __arr.tag.email will result in an undefined error, because it's an array not an object.
Therefore what you could do is, if you don't know exactly the index:
var __arr = [];
__arr.push(['id' ,'12541']);
__arr.push(['tag', {"sub":false,"email":"email#email.com"}]);
for (var i = 0; i < __arr.length; i++){
if(__arr[i][0] === 'tag'){
console.log(__arr[i][1].email);
break;
}
}

so you have an array as __arr, the first element you are pushing is id which is an array second array is having your email id.
so you can access as shown below.
I hope this will solve your issue
var __arr = [];
__arr.push(['id' ,'12541']);
__arr.push(['tag', {"sub":false,"email":"email#email.com"}]);
console.log("email id =>", __arr[1][1].email)

I hope you know array is starting from its index that's base value is 0. in your code there is no such element which is available in index 2.
document.write(__ar[2][2]) //
I know lots of answer is given here, but i just want to tell you even you are pushing value in "__arr" i.e an array of array. so every element is storing in its index value.
var __arr = [];
__arr.push(['id' ,'12541']);
__arr.push(['tag', {"sub":false,"email":"email#email.com"}]);
console.log(__arr[0]) //return you ["id", "12541"]
console.log(__arr[1]) //return you ["tag", {sub: false, email: "email#email.com"}]
again you can see inside of your "__arr" there is a an array element
console.log(__arr[0][0]) //return you "id"
console.log(__arr[0][1]) //return you "12541"
console.log(__arr[1][0]) //return you "tag"
console.log(__arr[1][1]) //return you {sub: false, email: "email#email.com"}
and here what you want i.e.
console.log(__arr[1][1].sub) //return you false
console.log(__arr[1][1].email) //return you "email#email.com"

A dynamic way to do it (with level of 2 nested levels).
Basically, I used two nested loops and aggregated the emails into a list.
let __arr = []
__arr.push(['id' ,'12541']);
__arr.push(['tag', {"sub":false,"email":"email#email.com"}]);
__arr.push(['tag2', {"sub":false,"email":"2222#email.com"}]);
const emails = __arr.reduce((res, items) => {
items.forEach(elem => {
if (elem.email) res.push(elem.email)
})
return res
},[])
console.log(emails)
// [ 'email#email.com', '2222#email.com' ]

Related

Having a hard time trying to isolate part of array :(

Here is the array
[ 'michael#ecorp.com:qnyynf',
'esteban#ecorp.com:uneyrl',
'marquis#ecorp.com:gnlybe',
'denver#ecorp.com:eboreg',
'robin#ecorp.com:zbaxrl',
'royce#ecorp.com:gubznf',
'van#ecorp.com:fgnejnef',
'tony#ecorp.com:cnff',
'thomas#ecorp.com:zvpunry',
'dave#ecorp.com:gvttre',
'benjamin#ecorp.com:fhcrezna',
'napoleon#ecorp.com:guhaqre',
'luke#ecorp.com:enatre',
'santos#ecorp.com:zvpuryyr',
'orlando#ecorp.com:npprff',
'wilbur#ecorp.com:cevaprff',
'stan#ecorp.com:cnffjbeq',
'kurtis#ecorp.com:fhafuvar',
'dee#ecorp.com:fhzzre',
'timothy#ecorp.com:wrffvpn' ]
Im trying to move only the passwords for each email tried with indexing ':' but indexing commas breaks it.
still a noob trying to understand these types of arrays
How would you achieve this?
Thank you for your help!
Have you tried something like:
//define array (as you have)
const array = ["1a:1b", "2a:2b", "3a:3b", "4a:4b"];
//map each item within that array. 'item' in this context is any array item. So essentially below is similar to a 'for each' command.
const passwords_001 = array.map(item => {
//I'm splitting each string, using the colon as the marker for 'seperator'
//i.e anything before or after it will be it's own item in the 'itemAsArray' array
var itemAsArray = item.split(':');
//pop() is taking the last item of the relevant array and removing it, but also returning it.
//This can then be passed as an item for the array we are mapping i.e passwords_001
var password = itemAsArray.pop();
//return the password as the new array item
return password;
});
//log the passwords_001 array to see only the passwords returned
console.log(passwords_001);
//console output
//["1b", "2b", "3b", "4b"]
This?
console.log([ 'michael#ecorp.com:qnyynf', 'esteban#ecorp.com:uneyrl', 'marquis#ecorp.com:gnlybe', 'denver#ecorp.com:eboreg', 'robin#ecorp.com:zbaxrl', 'royce#ecorp.com:gubznf', 'van#ecorp.com:fgnejnef', 'tony#ecorp.com:cnff', 'thomas#ecorp.com:zvpunry', 'dave#ecorp.com:gvttre', 'benjamin#ecorp.com:fhcrezna', 'napoleon#ecorp.com:guhaqre', 'luke#ecorp.com:enatre', 'santos#ecorp.com:zvpuryyr', 'orlando#ecorp.com:npprff', 'wilbur#ecorp.com:cevaprff', 'stan#ecorp.com:cnffjbeq', 'kurtis#ecorp.com:fhafuvar', 'dee#ecorp.com:fhzzre', 'timothy#ecorp.com:wrffvpn' ]
.map(e => e.split(':')[1]));
Or this?
console.log([ 'michael#ecorp.com:qnyynf', 'esteban#ecorp.com:uneyrl', 'marquis#ecorp.com:gnlybe', 'denver#ecorp.com:eboreg', 'robin#ecorp.com:zbaxrl', 'royce#ecorp.com:gubznf', 'van#ecorp.com:fgnejnef', 'tony#ecorp.com:cnff', 'thomas#ecorp.com:zvpunry', 'dave#ecorp.com:gvttre', 'benjamin#ecorp.com:fhcrezna', 'napoleon#ecorp.com:guhaqre', 'luke#ecorp.com:enatre', 'santos#ecorp.com:zvpuryyr', 'orlando#ecorp.com:npprff', 'wilbur#ecorp.com:cevaprff', 'stan#ecorp.com:cnffjbeq', 'kurtis#ecorp.com:fhafuvar', 'dee#ecorp.com:fhzzre', 'timothy#ecorp.com:wrffvpn' ]
.map(e => e.split(':')[0]));

Push data into existing array using javascript

I am trying to find a way to build my custom array, but I am not able to do so.
What I have done so far:
I have my array constructed like so:
const super_array = [];
super_array.push({
produs: rezultate[i].produs,
email: rezultate[i].email,
pretDorit: rezultate[i].pretDorit
});
Further down into the code, I want to assign new data to the array, like so :
for(let j=0; j<results.length; j++) {
priceNumber = parseFloat(results[j].replace('<span>Lei</span>', '')) ;
super_array.push({price: priceNumber})
}
Result:
Right now, I get the following structure:
super_array({
produs: rezultate[i].produs,
email: rezultate[i].email,
pretDorit: rezultate[i].pretDorit
}, {pret: priceNumber});
What I would like to get is:
super_array({
produs: rezultate[i].produs,
email: rezultate[i].email,
pretDorit: rezultate[i].pretDorit,
pret: priceNumber
});
I am not sure if I have explained it correctly. Basically I want to have the priceNumber uniquely match with the other data in the existing array, and not to be added as a separate index.
super_array[0].pret = priceNumber
super_array.push adds a new object to the array. What you are trying to do in the last code is adding a property to an object of the array.
For example: super_array[0].pret = priceNumber will add the property pret with the value of priceNumber. Here I'm not adding new objects to the array.

Generating a new array if a certain criteria is met (Javascript)

I have an array of users who all need to be added to a group array. If the the group array has less than 3 users, i want to add the user to that group array. If the group array already has 3 user, I want to push the current group array to another array that collects all the groups and start another new group array for the next 3 users until there are no users.
Error -
let group[i] = [];
Unexpected token [
I have been racking my brains trying to figure this out. Maybe staring at the screen for too long.
This is what i have been trying with different variations but the console is not impressed -
function createGroups(totalPeople){
let i = 1
let group[i] = [];
let array = totalPeople
totalPeople.map((user) => {
if(group[i] =< 3){
group[i].push(user)
}else{
array.push(group[i]);
i++
}
})
};
totalPeople is an array created earlier in my code and this is the only part of the file that is not running as intended. Any help with a method on how to do this or suggestions on fixing this code would be of great help! thank you!
Try to initialize group as an array:
let i = 1
let group = [] // Initialize as an array
group[i] = [];
let array = totalPeople
totalPeople.map((user) => {
if(group[i] =< 3){
group[i].push(user)
}else{
array.push(group[i]);
i++
}
})
There are a few issues in your code :
function createGroups(totalPeople){
let i = 1
let group[i] = []; // issue #1
let array = totalPeople
totalPeople.map((user) => {
if(group[i] =< 3){ // issues #2 and #3
group[i].push(user)
}else{
array.push(group[i]); // issue #4
i++; // issue #5
}
})
};
Issue #1 :
You need to define group as an array before adding an index.
let group = [];
group[i] = [];
Issue #2 :
Looks like you meant to compare group[i].length and 3
Issue #3 :
Use <= instead of =< to compare your numbers. Also, if you compare the length with <= 3, you'll have 4 people per group. Because the first index in arrays is 0.
Issue #4 :
You are pushing to array, which is a reference to totalPeople. Is this what you meant? Because I doubt it will produce the expected results. You may want to initialize an empty array and push your group[i] array in it. And then, return that new array. It's usually a good practice in functionnal programming to return a new array and not modify the one passed as a parameter.
Issue #5 :
If you increment i, you need to initialize group[i] as an array, otherwise you won't be able to push in it when comes the next loop iteration.
Differnet logic :
Now that you fixed the issues in your code, here's a Snippet showing another way to do it using Array.prototype.reduce :
const totalPeople = ["Joe", "Jack", "Jerry", "Jane", "Mary", "Billy", "Vicky", "Bobby"];
const groupsOfThree = totalPeople.reduce((accumulator, currentPerson, index) => {
// pushing the current person in the topest group in the accumulator
accumulator[accumulator.length-1].push(currentPerson);
// if it's the 3rd person, we're pushing the an empty group in the accumulator
if (index % 3 === 2) {
accumulator.push([]);
}
return accumulator;
}, [[]]); // the initial value of the accumulator will be an array containing an empty group
console.log(groupsOfThree);

JavaScript function Array.prototype.includes() doesn't work in for loop

I have a web app that tracks your purchases and displays different statistics. In one of the pages I have jQuery ajax requests that load a user's purchases from an API call. Then all the purchases are put into a global array, called G_PURCHASES, as JavaScript objects.
So far so good. Then I call a function that uses jQuery's Deferred() to make it chainable; it iterates G_PURCHASES and gets all distinct purchase.item.category's (take a look at the purchase object's relevant structure) by checking if G_PURCHASES[i].item.category is included in another global array called G_CATEGORIES by using Array.includes(). And if it is not then push() it into G_CATEGORIES.
The error I have a problem with is that even after a category object has been pushed into the G_CATEGORIES array, the Array.includes() check still returns false, every time. Check the relevant code and output to clear it up.
// Relevant structure of the purchase object
purchase = {
item: {
category: {
categoryID: int,
name: string
}
}
// Relevant code
var G_PURCHASES = []; // array declared globally
// it is successfully filled with #purchase objects from another function
var G_CATEGORIES = []; // array declared globally
// to be filled by #LoadAllCategories
var LoadAllCategories = function() {
// make a jQuery Deffered
let func = $.Deferred(function() {
let allP = G_PURCHASES; // make a shortcut
let allC = C_CATEGORIES; // make another shortcut
for (var i = 0; i < allP.length; i++) {
// get whether the current purchase.item.category
// already exists in allC array
let exist = allC.includes(allP[i].item.category);
// console.log the above result
console.log('i = ' + i + ', category exists = ' + exist);
// if it doesn't exist then push it in
if (!exist) allC.push(allP[i].item.category);
}
this.resolve();
});
return func;
}
// Input
G_PURCHASES has 6 #purchase objects with 3 unique item.category 'ies
// Output
i = 0, category exists = false
i = 1, category exists = false
i = 2, category exists = false
i = 3, category exists = false
i = 4, category exists = false
i = 5, category exists = false
// Result
G_CATEGORIES contains duplicate categories
I tried to use Array.indexOf() and jQuery's $.inArray() with no success. No matter what I console.log() I can't seem to find where the error lies. So, if you can tell me why does Array.includes() doesn't work inside this for loop I will find you and I will buy you a beer!
Well includes checks for referential equality, so there might be two objects with same properties and values, but still they are different objects, thus their reference is not equal. You probably want to check every category object for their categoryID and name manually to find duplicates.

Split an object into array of objects based on a condition in JavaScript

How to split an object into array of objects based on a condition.
oldObject = {"Chicago, IL:Myrtle Beach, SC": 0.005340186908091907,
"Portsmouth, NH:Rock Hill, SC": 0.0063224791225441205,
"Columbia, SC:Laconia, NH": 0.006360767389277389,
"Council Bluffs, IA:Derry, NH": 0.0016636141225441225}
Above is the given sample object. I want to make an array of objects like this,
newArray = [{"city":"Chicago", "similarTo":"Myrtle"},
{"city":"Portsmouth", "similarTo":"Rock Hill"},
{"city":"Columbia", "similarTo":"Laconia"},
{"city":"Council Bluffs", "similarTo":"Derry"}]
I have been scratching my head with this for a while now. How can I get the above array(newArray)?
Here is a bunch of code you can try.
1) Iterate over oldObject and get the name of the property.
2) Split that name into an array based on the ":" character, since it separates the cities
3) Go over that new array, splitting it on the "," character (so as not to get the states).
4) Put the values into the newObject, based on whether it's the first or second part of the original property name.
5) Push that newObject, now with items, into a newArray.
Basically, this parses apart the name and does some array splitting to get at the right values. Hope it helps and helps you understand too.
var oldObject = {"Chicago, IL:Myrtle Beach, SC": 0.005340186908091907,
"Portsmouth, NH:Rock Hill, SC": 0.0063224791225441205,
"Columbia, SC:Laconia, NH": 0.006360767389277389,
"Council Bluffs, IA:Derry, NH": 0.0016636141225441225};
var newArray = [];
for (object in oldObject) {
var thisObjectName = object;
var thisObjectAsArray = thisObjectName.split(':');
var newObject = {
'city': '',
'similar_to': ''
};
thisObjectAsArray.forEach(function(element,index,array) {
var thisObjectNameAsArray = element.split(',');
var thisObjectNameCity = thisObjectNameAsArray[0];
if(index===0) {
newObject.city = thisObjectNameCity;
} else if(index===1) {
newObject.similar_to = thisObjectNameCity;
}
});
newArray.push(newObject);
}
console.log(newArray);
PS: to test, run the above code and check your Developer Tools console to see the new array output.

Categories