I have a function "Next "that maps an array like in the example below and after incrementing the element I am doing something, but I also have another function "Prev" it pretty much does a similar mapping but in that function, I am decrementing the element. The Next function works fine but the Prev function doesn't, can someone please help me with this?
I am mapping an array of object
[
{
"id":"v82b3a65",
"name":"Name"
},
{
"id":"u0b26551",
"name":"Name2"
}
]
my functions :
const Next = () => {
array.items.map((item, key, element) => {
var next = element[key ++];
setId(next.id);
});
};
const Prev = () => {
array.items.map((item, key, element) => {
var prev = element[key --];
setId(prev.id);
});
};
render(
<View>
<Button title={'Prev'} onPress={Prev}/>
<Button title={'Next'} onPress={Next}/>
</View>
)
I am using those functions in onPress of buttons
The result I need: on Next button press I want it to set setID = next objects id and on Prev button press I want to set setID = previous object id
You should check index value if it is larger than 0 in Prev function. Also check if it is smaller than array length - 1 in Next function.
const Next = () => {
var newArray = myArray.map(function (value, index, elements) {
if (index < myArray.length - 1) {
var next = elements[index + 1];
// do something
}
});
};
const Prev = () => {
var newArray = myArray.map(function (value, index, elements) {
if (index > 0) {
var next = elements[index - 1];
// do something
}
});
};
Related
This is the section of code I am dealing with,
This is my hook
const [array, setArray] = useState(
JSON.parse(localStorage.getItem("notes")) ?? []
);
And this is the function,
const save = () => {
let info = one.current.value;
console.log(newIndex, " and ", info);
console.log("this si array element -> ", array[newIndex - 1]);
array[newIndex - 1] = info;
if (newIndex !== undefined) {
setArray((e) => {
return e.map((e1, i) => {
if (i + 1 === newIndex) {
return [...e ];
}
});
});
}
};
info has the correct input I want to update to and newIndex have the index of the element I wish to update.
Can you suggest to me what I need to change in this section, this is part of the above function,
setArray((e) => {
return e.map((e1, i) => {
if (i + 1 === newIndex) {
return [...e ];
}
});
To update your array you do not need to map anything. You only need to copy the array, modify the copied array at the right index and return the copied array. React will take care of the rest.
It's important, that you copy the array, else react won't notice the change. useState only remembers the array's address in memory.. Only through a new array with a new address will useState actually fire.
Here is my take on what I think your save() function should look like:
const save = () => {
let info = one.current.value;
if (newIndex !== undefined) {
console.log(newIndex, " and ", info);
console.log("this is array element -> ", array[newIndex - 1]);
setArray((e) => {
let temp = [...e];
temp[newIndex - 1] = info;
return temp;
});
}
};
Tried the code in codesandbox and I think this is what you want.
I have a table. When I click on an element I return its index. How can I (starting from this element) display all elements with index + 9. i.e. if the selected element has index 0, then I also need to display elements with indexes 9, 18, 27, etc.
let newCell = [td#2, td#0, td#2, td#0, td#2, ..... td#1, td#0]
newCell.forEach((item, i) => {
item.addEventListener('click', () => {
console.log(i)
})
})
I have not included the code to "display" those elements that will come in the series, but below is the code that logs them out. You can update it to display them.
const DIFF = 9;
newCell.forEach((item, i) => {
item.addEventListener('click', ()=>logAllItemsInSeries(i));
}
const logAllItemsInSeries = (i) => {
console.log(i);
const series = [];
while (i < newCell.length) {
series.push(i);
i += DIFF;
}
series.forEach((index) => {
console.log(index);
console.log(newCell[index]);
});
};
What you need to do in this case is keep track of a count of what elements should be filtered out and then update that count as you filter through it. Unfortunately your cell data is unclear to me so I went ahead and made my own to explain.
let data = [];
for (let i = 0; i < 100; i++) {
data.push({ id: i });
}
function getByNine(id) {
let count = id + 9
return data.filter(i => {
if (i.id === count) {
count = count + 9
return i
} else {
return
}
})
}
console.log(getByNine(3))
Inside your event listener you would put a reference to the getByNine(i) function (or whatever you want to call it) and pass its index.
Inside this function you set a default count of 9 + whatever the id of the element clicked
Run a filter through your array of objects, when the count is correct return that item and then increment the count by 9 for the next correct element
function getByNine(i) {
// code here
}
newCell.forEach((item, i) => {
item.addEventListener('click', () => {
getByNine(i)
})
})
Check if the second array contains the first array's element then show that otherwise show the second array element (which is not in the first one)
var contacts = [{name:'muzz',no:1},{name:'muzamil',no:2},{name:'hamza',no:3}]
var recipient = ['2','4']
function check () {
contacts.forEach(({name,no}) => {
if(recipient.includes(no.toString())){
console.log('exists',name)
}
else {
recipient.forEach(e =>{
if(!recipient.includes(no.toString()) && contacts == no){
console.log(e);
}
})
}
})
}
kindly tell me what I am missing here. The else block again traverses all the elements
Is this what you want?
function resolve (a, b) {
const map = a.reduce((acc, {no}, i) => (acc[no] = a[i], acc), {})
return b.reduce((acc, el) => (acc.push(map[el]?.name ?? el), acc), [])
}
var contacts = [{name:'muzz',no:1},{name:'muzamil',no:2},{name:'hamza',no:3}]
var recipients = ['2','4']
const resolved = resolve(contacts, recipients)
console.log(resolved)
You can loop through the recipient array first, then filter the object from the contacts array by matching the current recipient:
var contacts = [{name:'muzz',no:1},{name:'muzamil',no:2},{name:'hamza',no:3}]
var recipient = ['2','4']
function check () {
recipient.forEach(r => {
var c = contacts.filter(c => c.no == r);
if(c.length){
console.log('exists',c[0].name)
}
else {
console.log(r);
}
});
}
check();
i'm a newbie on JavaScript, help me to fix the problem i got.
I have an array, i want to remove class list for other div which are not same with the current index. Please help
i tried to find the answer from other discussion, but i still don't get what i want.
Here's the code:
window.addEventListener("load", ()=> {
const sounds = document.querySelectorAll(".sound");
const pads = document.querySelectorAll(".pads div");
const visual = document.querySelector(".visual");
pads.forEach((pad, index) => {
pad.addEventListener("click", function() {
sounds[index].currentTime = 0;
sounds[index].play();
popUpNote();
const ind = index + 1;
//I Need to got the other index from the current index,
//like if current index is 2, then i want to get 0,1,3,4,5
//since i have 6 index inside
pad.classList.add("active-pad"+ind);
sounds[index].addEventListener("ended", function() {
const noteChild = document.querySelector(".visual div");
noteChild.remove();
pad.classList.remove("active-pad"+ind);
});
});
});
const popUpNote = () => {
const note = document.createElement("div");
visual.appendChild(note);
note.style.animation = 'beatOn 1.5s ease-in-out infinite both';
};
});
I want to got the other index from the current index, like if the current index is 2, then i want to get 0,1,3,4,5 since i have 6 index inside
Through this , might you get your solution ,
In this JS script , you will not get the current index .
var arr = [1 , 2 , 3 , 4 , 5 , 6];
arr.forEach(function(valuw , index){
console.log(valuw , index);
for(var i = 0 ; i < arr.length ; i++){
if( i != index){
console.log("index at " , index , "itereator ===>" , i+1);
}
}
});
Use Array.filter() to find the other indexes:
const idxs = [0,1,2,3,4,5,6,7,8,9,10]
const cur = 4
const res = idxs.filter(idx => idx !== cur)
console.log(res)
I have a for loop running agains a node list. I am trying to run through the node list and trigger a click then i set an interval to wait for a popup then i want to trigger a click within the popup.
My issue is i need each iteration to wait until the popup is loaded and the item in the popup as been clicked before going to the next iteration. Hope this makes sense.
Here is my code.
let checkSteats = () => {
const seats = document.querySelectorAll(seatSectionSelector);
if (seats.length < maxSeatCount) {
maxSeatCount = seats.length;
}
if (seats.length > 0) {
[].forEach.call(seats, (seat, index) => {
/**
* WE NEED TO CLICK WAIT FOR A CHANGE IN THE RESPONSE OR POP UP BEFORE WE GO INTO THE NEXT ITERATION
*/
console.log(seat)
if ((index+1) <= maxSeatCount) {
seat.dispatchEvent(
new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: true,
buttons: 1
})
);
const popupInterval = setInterval(() => {
const popupBtn = document.querySelector('.ticket-option__btn');
if (popupBtn) {
popupBtn.click();
clearInterval(popupInterval);
}
}, 100)
}
});
}
};
You want to use a basic queue where you pull the item off from the front of the array with shift()
var myArray = [1, 2, 3, 4]
function nextItem() {
var item = myArray.shift();
window.setTimeout(function() {
console.log(item);
if (myArray.length) nextItem();
}, 1000)
}
nextItem()
So in your case, you would call nextItem() when you clear the interval. You can get shift by converting the html collection to an array
const seats = Array.from(document.querySelectorAll(seatSectionSelector));
function nextItem() {
var seat = seats.shift();
seat.dispatchEvent(...);
const popupInterval = setInterval(() => {
...
if (popupBtn) {
...
if (seats.length) nextItem();
}