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)
}
Related
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]));
I'm super newbie in coding and I need help to achieve this code.
I'm trying to get a random item (in pairs) from an array and then remove it from this array until user gets to the last item or 60 days have gone from using the service (cookie?)... I have build a script with the help of other questions here in stackoverflow and here is my results so far.
`<script>
var randomizer = document.getElementById("getImgBut");
var dog1 = '/app/wp-content/mediaApp/yo-creo-mi-realidad/01F.jpg';
var dog2 = '/app/wp-content/mediaApp/yo-creo-mi-realidad/01B.jpg';
var dogpics=[dog1,dog2];
var yourPics = [
dogpics,
[ '/app/wp-content/mediaApp/yo-creo-mi-realidad/02F.jpg', '/app/wp-content/mediaApp/yo-creo-mi-realidad/02B.jpg' ],
[ '/app/wp-content/mediaApp/yo-creo-mi-realidad/03F.jpg', '/app/wp-content/mediaApp/yo-creo-mi-realidad/03B.jpg' ],
[ '/app/wp-content/mediaApp/yo-creo-mi-realidad/04F.jpg', '/app/wp-content/mediaApp/yo-creo-mi-realidad/04B.jpg' ],
[ '/app/wp-content/mediaApp/yo-creo-mi-realidad/05F.jpg', '/app/wp-content/mediaApp/yo-creo-mi-realidad/05B.jpg' ],
[ '/app/wp-content/mediaApp/yo-creo-mi-realidad/06F.jpg', '/app/wp-content/mediaApp/yo-creo-mi-realidad/06B.jpg' ] //This array has 52 cards but I cutted it for example purposes
];
function get_random_number(array){
return Math.floor(Math.random() * array.length |0);
} // here is where I have tried to modify with other scripts like the one in this page https://stackoverflow.com/questions/38882487/select-random-item-from-array-remove-it-restart-once-array-is-empty with no success
randomizer.addEventListener("click", function() {
var rand_number = get_random_number(yourPics);
console.log(rand_number);
document.getElementById('img1').src = yourPics[rand_number][0];
document.getElementById('img2').src = yourPics[rand_number][1];
});
var card = document.querySelector('.card');
card.addEventListener( 'click', function() {
card.classList.toggle('is-flipped');
});
</script>`
Thank you for your help!
I don't fully understand what you mean by "remove in pairs", but I'll answer presuming you mean you wish to remove the image ending in 02F.jpg at the same time as removing the image ending in 02B.jpg, and then 03F.jpg at the same time as 03B.jpg.
The solution to this that I will propose is that we will structure your data a bit differently to begin with. That is, if those images, the "B image" and "F image" are linked, we could keep them in the same `javascript object. This would look like:
var yourPics = [
{
bImage: '/app/wp-content/mediaApp/yo-creo-mi-realidad/02F.jpg',
fImage: '/app/wp-content/mediaApp/yo-creo-mi-realidad/02B.jpg'
},
{
bImage: '/app/wp-content/mediaApp/yo-creo-mi-realidad/03F.jpg',
fImage: '/app/wp-content/mediaApp/yo-creo-mi-realidad/03B.jpg'
}...]
This would then be an array of objects, rather than strings. We can access the bImage property of an object with just
myObject = yourPics[0]
myObject.bImage
We could delete one of those objects those at random via splice.
myRandomlyRemovedObject = yourPics.splice(myIndexToDeleteFrom, 1) would remove 1 object from yourPics at position of myIndexToDeleteFrom, which you presumably would choose randomly. myRandomlyRemovedObject would be assigned to the one object we removed.
I think this object based approach is safer since you will know for a fact that you will removed both matching strings at the same time.
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' ]
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);
I have a list that I took from a converted CHANGELOG.md file, and it looks like this:
["[3.0.0]","Features", "changes done in file","[2.0.1]", "Bug Fixes", "fixed login"]
What I want to do is to separate each version into its own list, like this:
["[3.0.0]", "Features", "changes done in file"],
["[2.0.1]", "Bug Fixes", "fixed login"]
Obviously, because it's a changelog, there can be multiple features and multiple bugfixes in a single version, so I want to a piece of code that separates the code appropriately.
I tried using if (string.startsWith('[')) but i couldn't manage to fit it in a loop.
Any help is appreciated.
Here's something I came up with. The code basically loops through the input array and adds each string to a currentArray variable. Everytime it hits a [ it puts the currentArray into the output and clears currentArray. At the end it removes the first element as the first element of the output will always be an empty array (since the first element of the input starts with a [)
var input = ["[3.0.0]","Features", "changes done in file","[2.0.1]", "Bug Fixes", "fixed login"];
var output = [];
var currentArray = [];
for (var i = 0; i < input.length; i++) {
if (input[i].charAt(0) == '[') {
output.push(currentArray);
currentArray = [];
}
currentArray.push(input[i]);
}
output.push(currentArray);
currentArray = [];
//Since it will take the first one, and put empty one, need to do last step.
output.splice(0, 1);
console.log(output);
// ["[3.0.0]", "Features", "changes done in file"],
// ["[2.0.1]", "Bug Fixes", "fixed login"]
Assuming that you're always working in sets of three, this is a quick and ugly approach
var data = ["[3.0.0]","Features", "changes done in file","[2.0.1]", "Bug Fixes", "fixed login"],
items = [];
data.map( (el, idx) => {
var last = items.length;
if( idx % 3 === 0 ) {
items.push( [] );
last += 1;
}
last = items[ last - 1 ];
last.push( el );
} );
console.log( JSON.stringify( items ) );
Here's an alternative solution should you prefer it:
const arr = ["[3.0.0]","Features", "changes done in file","[2.0.1]", "Bug Fixes", "fixed login"];
const newArr = [];
let tempArr = [];
arr.forEach(function(v, i) {
if(/^\[\d+.\d+.\d\]$/.test(v) && i > 0) {
newArr.push(tempArr);
tempArr = [v];
} else {
tempArr.push(v)
}
});
newArr.push(tempArr);
console.log(newArr);
This snippet loops through the items one-by-one. It uses two arrays, one to hold the final result and one to populate with items for the current version.
I am using a regex to check if the item contains one [ followed by a number, then a period, number, period, number and finally the trailing ]. This allows the other strings that are not version tags to contain that character.
If the current item is a version tag, we push tempArr (which contains the changes of the current version that we've previously filled in our loop) to our result array newArr. Then, we empty the tempArr and give it the starting value of the next version tag.
If it is not, we just push the current item to our temporary array.
It would be interesting to know if you were guaranteed to get this data in triplets, as your example seems to imply. If you knew this up front, there are many creative solutions that could emerge. For just creating a 2D Array, however, I like this approach (you can run this directly in node.js to try it out):
const original = ['[3.0.0]', 'Features', 'changes done in file', '[2.0.1]', 'Bug Fixes', 'fixed login']
function transformToChangeLog (originalArray) {
const changeLog = originalArray.reduce((newList, element) => {
element.charAt(0) === '[' // check for version string
? newList.push([element]) // If version string, then push a new Array containing that string
: newList[newList.length - 1].push(element) // If something else, tack it onto the last Array in the changelog list
return newList // whatever is returned in the reduce function is passed to the next iteration, allowing us to build this 2D array one element at a time.
}, [])
return changeLog
}
console.log(transformToChangeLog(original))
I hope that helps! I like the reduce Array method, because of it's versatility and succinctness.