I create new array and add to her specific values. I add in first index and first index has value, but if I add in second or more index, last indexes are empty and I don't know why. Here my code.
const inputs = [...document.querySelectorAll('.input')];
let timeout = null;
inputs.forEach((input, index) => {
input.addEventListener('keyup', () => {
clearTimeout(timeout);
let inputValue = Number(input.value);
timeout = setTimeout(() => {
if (index !== 1) {
let arr = [];
if (index === 0) {
arr[0] = inputValue;
} else if (index === 2) {
arr[1] = inputValue;
} else if (index === 3) {
arr[2] = inputValue;
} else if (index === 4) {
arr[3] = inputValue;
}
console.log(arr);
}
}, 1000);
});
});
Use of the "push" array function. Example:
const inputs = [...document.querySelectorAll('.input')];
let timeout = null;
let arr = [];
inputs.forEach((input, index) => {
input.addEventListener('keyup', () => {
clearTimeout(timeout);
let inputValue = Number(input.value);
timeout = setTimeout(() => {
arr.push(inputValue);
console.log(arr);
}, 1000);
});
});
Related
examples:
"heLLo" => 0.1.2.2.3
"javAscript" => 0.1.2.1.3.4.5.6.7.8
"hippopotomonstrosesQuippedaliophobia" => 0.1.2.2.3.2.3.4.3.5.3.6.7.4.8.3.7.9.7.10.11.1.2.2.9.12.13.14.1.3.2.0.3.15.1.13
my non-working code:
function wordPattern(word) {
var res = []
var dic = []
var count = 0
var pipa = word.toLowerCase().split("")
for (i=0;i<pipa.length;i++) {
if (!dic.includes(pipa[i])) {
dic.push({key: count, value: pipa[i]});
count ++
}
for (j=0;j<pipa.length;j++) {
res.push(dic.key[pipa[i]])
}
return res.join(".");
}
Thanks in advance
To associate characters to numbers, don't use an array, use an object:
function wordPattern(word) {
const numbersByChar = {};
let i = 0;
return [...word]
.map(char => numbersByChar[char] ?? (numbersByChar[char] = i++))
.join('.');
}
console.log(wordPattern('hello'));
console.log(wordPattern('hippopotomonstrosesquippedaliophobia'));
Or without the concise syntax that you might find more readable
function wordPattern(word) {
const numbersByChar = {};
let i = 0;
return Array.from(word)
.map((char) => {
if (numbersByChar[char] === undefined) {
numbersByChar[char] = i;
i++;
}
return numbersByChar[char];
})
.join('.');
}
console.log(wordPattern('hello'));
console.log(wordPattern('hippopotomonstrosesquippedaliophobia'));
hint 1 is that you can get a letter like: word[index]
so change your code to this:
function wordPattern(word) {
var res = []
var dic = []
var count = 0
for (i=0;i<word.length;i++) {
let dicItem = dic.find(x=>x.value==word[i]);
if(!dicItem) {
dic.push({key: count, value: word[i]});
res.push(count);
count ++;
}
else res.push(dicItem.key);
}
return res.join(".");
}
I want to change the index of newAr on each click and console log the values of next object in newAr showed in looper function
Note: I only want the index second object values on second click and third object values in newAr on third click
HTML only has a button nothing else
const button = document.querySelector("button");
let firstVar = () => {
const firstVarVariable = Math.round(Math.random() * 10);
if (firstVarVariable < 5) {
return true;
} else {
return false;
}
};
let secondVar = () => {
const firstVarVariable = Math.round(Math.random() * 10);
if (firstVarVariable < 5) {
return true;
} else {
return false;
}
};
let thirdVar = () => {
const firstVarVariable = Math.round(Math.random() * 10);
if (firstVarVariable < 5) {
return true;
} else {
return false;
}
};
const newAr = [];
const pusher = () => {
newAr.push({
one: firstVar(),
two: secondVar(),
three: thirdVar(),
});
console.log(newAr);
looper();
};
const looper = () => {
for (const value of newAr) {
console.log(value.one);
console.log(value.two);
console.log(value.three);
}
// I want to change the index of newAr array on click
// Like i want to console log first object in array on first click
// and second object on other click and third object
// alsp please tell me if i can change some approch
};
button.addEventListener("click", () => {
pusher();
});
let randomBool = () => Math.random() < 0.5;
// all three functions did the same thing...
const newAr = [];
const pusher = () => {
newAr.push({
one: randomBool(),
two: randomBool(),
three: randomBool(),
});
console.log(newAr);
looper();
};
let index = 0; // counter / array index
const looper = () => {
let value = newAr[index++]; // always getting the next element (starting from 0).
console.log(value.one);
console.log(value.two);
console.log(value.three);
};
/***/
const button = document.querySelector("button");
button.addEventListener("click", () => {
pusher();
});
<button>Test</button>
First of all I want to know if I am right about cause of the problem.
const updateScore = (isCorrect) => {
// Update Game Variables
if (isCorrect === true) {
counter++;
score += 100;
}
};
// Reset Styling
const resetLoadedQuestionStyling = (isCorrect) => {
questionScreen.style.display = 'none';
answerArr.forEach(answer => {
answer.classList.remove('correct');
answer.classList.remove('wrong');
answer.classList.remove('disable');
});
updateScore(isCorrect);
};
const styleAnswer = (div, isCorrect) => {
if (isCorrect === true) {
div.classList.add('correct');
} else {
div.classList.add('wrong');
for (let i = 0; i < answerArr.length; i++) {
if (i === currentQuestion.correct) {
answerArr[i].classList.add('correct');
}
}
}
// Prevent Second Check
answerArr.forEach(answer => {
answer.classList.add('disable');
});
// Reset Styling
setTimeout(() => {
resetLoadedQuestionStyling(isCorrect);
}, 3000);
};
const checkAnswer = (div, index) => {
const userChoice = index;
// Default Answer State
let isCorrect = false;
if (userChoice === currentQuestion.correct) {
isCorrect = true;
}
styleAnswer(div, isCorrect);
};
answerArr.forEach((div, index) => {
div.addEventListener('click', () => {
checkAnswer(div, index);
});
});
My counter updates 1,time, that 2 times... and I think the cause of this issue is that my EventListener is in a forEach loop, is that right?
How to prevent it?
Thanks!
EDIT: Addded more of the code in order to get my idea better.
EDIT: answerArr is array of 4 divs in my HTML
There may be a setTimeout-related issue. Every time an answer is clicked, the counter is set to be incremented after 3 seconds.
Here's the sequence when an answer is clicked:
'click'
checkAnswer ->
styleAnswer ->
setTimeout =>
resetLoadedQuestionStyling ->
updateScore ->
counter++
Below is the code with all of the unrelated lines removed. It does increment the counter after every click, but only after 3 seconds.
const answerArr = [...document.querySelectorAll('button')];
let counter = 0;
const span = document.getElementById('counter');
const updateScore = (isCorrect) => {
if (isCorrect === true) {
counter++
}
span.innerText = counter;
}
const resetLoadedQuestionStyling = (isCorrect) => {
updateScore(isCorrect)
}
const styleAnswer = (div, isCorrect) => {
// Reset Styling after 3 seconds
setTimeout(() => {
resetLoadedQuestionStyling(isCorrect);
}, 3000);
}
const checkAnswer = (div, index) => {
styleAnswer(div, true);
}
answerArr.forEach((div, index) => {
div.addEventListener('click', () => {
checkAnswer(div, index);
});
});
<button>Answer 1</button><br>
<button>Answer 2</button><br>
<button>Answer 3</button><br>
<button>Answer 4</button><br>
<p>Counter: <span id="counter"></span></p>
the problem statement is i have to make a search function in which i can search lower can upper case element both even if i type lower case either upper case
i tried upper case search and lower case but its not working at all please suggest me as soon as possible
search(searchValue) {
if (searchValue != null && searchValue != "") {
var searchItem = searchValue;
var allOppData = this.stagesWiseOpportunitiesData;
var filtered = _.mapValues(allOppData, statuses =>
_.filter(statuses, statusT =>
_.some(statusT, T => _.includes(T, searchItem))
)
);
this.stagesWiseOpportunitiesData = filtered;
let stages = this.opportunitiesStateReason;
stages.forEach(element => {
let num = this.stagesWiseOpportunitiesData[element.orderData].reduce(
function(sum, value) {
return sum + value.expected_revenue;
},
0
);
element.totalExpectedRevenue = num.toFixed(2);
});
} else {
this.stagesWiseOpportunitiesData = this.stagesWiseOpportunitiesDataCopy;
let stages = this.opportunitiesStateReason;
stages.forEach(element => {
let num = this.stagesWiseOpportunitiesData[element.orderData].reduce(
function(sum, value) {
return sum + value.expected_revenue;
},
0
);
element.totalExpectedRevenue = num.toFixed(2);
});
}
}
}
Try like this. you have missed to return the for the search function.
NOTE: you have only returned for a function inside search function
function search(searchValue) {
if (searchValue != null && searchValue != "") {
var searchItem = searchValue;
var allOppData = this.stagesWiseOpportunitiesData;
var filtered = _.mapValues(allOppData, statuses =>
_.filter(statuses, statusT =>
_.some(statusT, T => _.includes(T, searchItem))
)
);
this.stagesWiseOpportunitiesData = filtered;
let stages = this.opportunitiesStateReason;
return stages.forEach(element => {
let num = this.stagesWiseOpportunitiesData[element.orderData].reduce(
function(sum, value) {
return sum + value.expected_revenue;
},
0
);
element.totalExpectedRevenue = num.toFixed(2);
});
} else {
this.stagesWiseOpportunitiesData = this.stagesWiseOpportunitiesDataCopy;
let stages = this.opportunitiesStateReason;
return stages.forEach(element => {
let num = this.stagesWiseOpportunitiesData[element.orderData].reduce(
function(sum, value) {
return sum + value.expected_revenue;
},
0
);
element.totalExpectedRevenue = num.toFixed(2);
});
}
}
console.log(search("Test"))
following adds items to array:
var arrayOptions = [];
function AddToFilterOptionList(mode) {
arrayOptions.push(mode);
}
remove item from array:
function RemoveFromFilterOptionList(mode) {
var index = arrayOptions.indexOf(mode);
if (index !== -1) {
arrayOptions.splice(index, 1);
}}
for example if i call
AddToFilterOptionList('APPLE') - APPLE should be added to array.
If i again call
AddToFilterOptionList('APPLE+FRUIT') - it should remove the the item 'APPLE' from array arrayOptions and should add APPLE+FRUIT
Any time only one word that starts with APPLE can be in array.
How to find the word like 'APPLE' in javascript.
I tried with Match() which returns the matching word. IndexOf() returns 1 only if whole word is match but not start of word.
Cycle through the Array and then use the startsWith method.
void AddToFilterOptionList(String mode) {
for (i=0; i<arrayOptions.length; i++) {
if (mode.startsWith(arrayOptions[i] == 1)) {
array[i] = mode;
return; // found, so return
}
}
arrayOptions.push(mode); // should only get here if string did not exist.
}
You need to split by + characted and then loop over produced array to add/remove all items:
var arrayOptions = [];
function AddToFilterOptionList(mode) {
mode.split(/\+/g).forEach(function(el) {
var index = arrayOptions.indexOf(el);
if (index !== -1) {
arrayOptions.splice(index, 1);
}
else {
arrayOptions.push(el);
}
});
}
function RemoveFromFilterOptionList(mode) {
var index = arrayOptions.indexOf(mode);
if (index !== -1) {
arrayOptions.splice(index, 1);
}
}
AddToFilterOptionList('APPLE');
document.write('<p>' + arrayOptions); // expect: APPLE
AddToFilterOptionList('APPLE+FRUIT');
document.write('<p>' + arrayOptions); // expect: FRUIT
AddToFilterOptionList('APPLE+FRUIT+CARROT');
document.write('<p>' + arrayOptions); // expect: APPLE,CARROT
This will work assuming the 'this+that' pattern is consistent, and that we only care about the starting item.
http://jsbin.com/gefasuqinu/1/edit?js,console
var arr = [];
function remove(item) {
var f = item.split('+')[0];
for (var i = 0, e = arr.length; i < e; i++) {
if (arr[i].split('+')[0] === f) {
arr.splice(i, 1);
break;
}
}
}
function add(item) {
remove(item);
arr.push(item);
}
UPDATE:
function add (array, fruits) {
var firstFruit = fruits.split('+')[0]
var secondFruit = fruits.split('+')[1]
var found = false
var output = []
output = array.map(function (item) {
if (item.indexOf(firstFruit) > -1) {
found = true
return fruits
}
else return item
})
if (! found) {
array.push(fruits)
}
return output
}
var fruits = []
add(fruits, 'APPLE')
fruits = add(fruits, 'APPLE+GRAPE')
console.log(fruits[0]) // 'APPLE+GRAPE'
fruits = add(fruits, 'APPLE')
console.log(fruits[0]) // 'APPLE'
Try this, the code is not optimised though :P
<html>
<head>
<script src = "jquery-1.10.2.min.js"></script>
<script type = "text/javascript">
var itemList = [];
function addItem()
{
var item = $('#item').val();
if(item != '' || item != 'undefined')
{
if(itemList.length == 0)
itemList.push(item);
else
{
for(i=0;i<itemList.length;i++)
{
var splittedInputItems = [];
splittedInputItems = item.split("+");
var splittedListItems = [];
splittedListItems = itemList[i].split("+");
if(splittedListItems[0] == splittedInputItems[0])
{
itemList.splice(i,1);
itemList.push(item);
return;
}
}
itemList.push(item);
}
}
}
</script>
</head>
<body>
<input id="item" type = "text"/>
<input type = "button" value="Add" onclick="addItem()">
</body>
</html>
let items = [1, 2, 3, 2, 4, 5, 2, 7];
let item = 2;
for (let i = 0; i < items.length; i++) {
if (items[i] === item) {
items.splice(i, 1);
i = i - 1;
}
}
If you want to remove the element '2' from items array, it is a way.