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

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]));

Related

How to array.splice from both ends simultaneously in Javascript?

How do you splice from both ends of an array either simultaneously or sequentially such that "leftsplice" number of fields are spliced from left and "rightsplice" number of fields are spliced from original array not the one after doing leftsplicing. Any tips?
const [skillname,setSkillName] = useState(["Engineering", "Product", "Organization", "Business", "Market", "Customer"]);
setSkillName(skillname => skillname.splice(0,leftsplice))
let temp=-5+leftsplice;
setSkillName(skillname => skillname.splice(temp, rightsplice))
This is doing only leftsplicing.
PS: leftsplice, rightsplice are working as desired. I console.logged them
Your code in splicing is okay, but you should only use setSkillName after both leftsplice and rightsplice is done by saving it on a temporary variable, I haven't tested this code below but it is answering the question "How to splice both at the same time from a state" :
function whatever() {
let tempSkillName = [...skillname]
tempSkillName = tempSkillName.splice(0,leftsplice))
let temp=-5+leftsplice;
tempSkillName = tempSkillName.splice(temp, rightsplice))
setSkillName(tempSkillName)
}

How to insert array data into json object in react js

I have a languages array. I need to insert my array data into Json Objeatc within a function.
I am a new student and I tried to do this using map. But it only inserts one data of array into a JSON object. But I need to insert all off array data one by one. But I don't know the way to that.IF anyone can help me with that it's really mean to me. Thank you.
This is how I need to be my JSON object:-
"displayNameLocalization": {
"en": "Fruits",
"fr": "des fruits",
"ja": "果物"
}
const data = {
displayNameLocalization : {},
};
const languages = ['En', 'Ta', 'Fr'];
function testFinalValue() {
displayNameLocalization.map((item) => {
data.displayName = item;
});
}
that's because you are overwritten the same variable in each loop of map, because there will be one element in data with name displayName , so in each loop you are affecting w new value to the same element that's why you input has just one value affected.
Can you afford an example of the input and the output that you want to get so I can help you with the code.

Get value from javascript nested array

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' ]

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);

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