I would like to run a script that repeats 100 times.
With each repetition it should be in order
Take the names from an array or list and pass them to my variable. How can I do this ?
I created this as an example and think about how I can install a function there. I've read and tried a few things. But somehow I'm not ready yet
var TestNames = ["test1", "test2", "test3", "test4", "test5"]
var n = TestNames[0]
interval = setInterval(function() {
var Username = n;
console.log(Username);
// here is some code
}, 2000);
setTimeout(function() {
clearInterval(interval)
}, 10000);
Aassuming the setTimeout is calculcated by the amount of names (10000/2000), you can omit it entirely.
const TestNames = ["test1", "test2", "test3", "test4", "test5"];
//REM: https://developer.mozilla.org/en-US/docs/Web/API/setInterval
//REM: Passing a copy of TestNames to not alter the original
const interval = setInterval(function(listOfNames){
if(listOfNames.length){
//REM: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift
const Username = listOfNames.shift();
console.log('Current name:', Username);
console.log(TestNames.length - listOfNames.length, ' names done.');
console.log(listOfNames.length % TestNames.length, ' names left.')
}
else{
//REM: Cancel the interval, if listOfNames has no more items
clearInterval(interval);
console.log('No names left.')
}
}, 2000, Array.from(TestNames));
Take the names from an array or list and pass them to my variable. How
can I do this ?
That depends on your requirements.
Do you need to keep TestNames?
Do you pick a random name?
Do you just pick the next name in order?
In my example I pass a copy of TestNames to the interval as listOfNames. On each iteration I remove the first item from listOfNames by using shift which also returns that removed item and assign it to Username. If listOfNames has no more items, the interval gets cleared.
const TestNames = ["test1", "test2", "test3", "test4", "test5"]
let index = 0
const interval = setInterval(function() {
const Username = TestNames[index];
console.log(Username);
index += 1
}, 2000);
setTimeout(function() {
clearInterval(interval)
}, 10000);
If you want to write a username for each iteration, I suggest this. Also note the use of const and let
const testNames = ["test1", "test2", "test3", "test4", "test5"]; // JS arrays starts at 0
const numberOfNames = testNames.length;
let counter = 0;
let interval = setInterval(function() {
if (counter >= numberOfNames) return; // don't continue
let Username = testNames[counter];
console.log(counter,Username);
counter++; // point at the next or perhaps beyond - shorthand for counter = counter + 1 or counter += 1. ++ increments
// here is some code
}, 2000);
let tId = setTimeout(function() {
clearInterval(interval)
}, 10000);
Related
I have an array of ID's ("world") to iterate. If the world element value exists as myArray[n].id then I want to delete the entire element in myArray. If not, then I want to add it to myArray.
world = ["12424126","12461667","12492468","12761163"]
myArray = [
{"id": "12424126"},
{"id": "12761163"},
{"id": "12492468"}
]
Example: if the first element in world[n] ("12424126") exists in myArray as {"id": "12424126"} then delete the element {"id": "12424126"}
if the first element in world[n] ("12424126") does not exists in myArray, then
myArray.push ({"id":world[n]});
}
for (n = 0; n <= world.length; n++) {
ID = world[n];
finished = false;
if (myArray.find(x => x.id === ID)) {
var index = _.findIndex(myArray, { "id": ID });
if (index > -1) { myArray.splice(index, 1);
finished = true;}
}
if (!finished) // PROBLEM: THE RECORD IS ADDED REGARDLESS OF FINISHED T/F
{myArray.push ({id:ID }); // HOW CAN I FIX THIS ?
}
}
The following code works as you want
world = ["12424126", "12461667", "12492468", "12761163"];
myArray = [{ id: "12424126" }, { id: "12761163" }, { id: "12492468" }];
for (n = 0; n < world.length; n++) {
ID = world[n];
var index = myArray.findIndex((item) => item.id == ID);
if (index > -1) {
myArray.splice(index, 1);
} else {
myArray.push({ id: ID });
}
}
The problem is that your loop will make finished turn from true to false again in a next iteration of the loop. You would need to exit the loop immediately when finished is set to true.
However, this can be better solved with a Set:
const world = ["12424126","12461667","12492468","12761163"];
let myArray = [{"id": "12424126"},{"id": "12761163"},{"id": "12492468"}];
const set = new Set(myArray.map(({id}) => id).concat(world));
myArray = Array.from(set, id => ({id}));
console.log(myArray);
If you don't want to assign to myArray a new array, and not create new objects for those that already existed in the array, then:
const world = ["12424126","12461667","12492468","12761163"];
let myArray = [{"id": "12424126"},{"id": "12761163"},{"id": "12492468"}];
const set = new Set(myArray.map(({id}) => id).concat(world));
myArray.push(...Array.from(set).slice(myArray.length).map(id => ({id})));
console.log(myArray);
This second solution assumes however that myArray did not already have duplicate id values.
I would like to count the amount of times that a value appears in an array, and delete the repeated values keeping just the first.
So I can store in another array the amount of times that it appears, and it will have the same index as the value in the other array.
The loops I have tried don't count the amount of times correctly or delete other values that shouldn't be the ones deleted.
var itemCount = [];
var itemsName = ["aaa", "bbb", "aaa", "ccc", "ddd", "ddd"]
for (let index = 0; index < itemsName.length; index++) {
for (var i = index + 1; i < itemsName.length; ++i) {
itemCount[index] = 1
if (itemsName[i] === itemsName[index]){
itemCount[index]++;
itemsName.splice(i, 1)
}
}
if (itemCount[index] > 1) {
console.log(itemsName[index] + itemCount[index])
} else {
console.log(itemsName[index])
}
}
So the output should be like,
aaa3 bbb ccc ddd2
I made some changes to your code
const itemsName = ["aaa", "bbb", "aaa", "ccc", "ddd", "ddd"];
const itemCount = {}; // It's better to set this as an object.
for (let index = 0; index < itemsName.length; index++) {
// index is a key and not the value of the array.
// itemsName[index] will give you the value of an item in the array
// Here I check if the key exists, incrementing it or setting it to 1.
if (itemCount[itemsName[index]]) itemCount[itemsName[index]]++;
else itemCount[itemsName[index]] = 1;
}
for (let key in itemCount) {
console.log(key + itemCount[key]);
}
If you remove an entry from an array you change the index of subsequent entries. Thus you cannot keep the old index in the new array you create for duplicates.
What you can do is create two separate arrays, one without duplicates, the other containing objects with the duplicates and their index.
var itemsName = [...];
var newArray = [];
var duplicatesArray = [];
var duplicateCount = 0;
// map creates a new array with the return statement
newArray = itemsName.map((entry,index) => {
// check if the new array includes the current entry iteration
if ( newArray.inculdes(entry) ) {
duplicateCount++; // just the duplicate counter
let duplicate = { oldIndex: index, value: entry }; // duplicate entry containing the oldIndex well .. index. This is so that you can get the index of the entry in the old array.
duplicatesArray.push(duplicate); // add entry to duplicateArray
return; // finish iteration without adding the entry to the new array
}
return e; // add iteration entry to the new array
});
This should be it. =)
Instead of using an array to keep track of the item count, use an object instead. You can use the item name as object key to quickly find the current count and increment it.
const itemsName = ["aaa", "bbb", "aaa", "ccc", "ddd", "ddd", "1", 1];
const itemCount = {};
for (const name of itemsName) {
itemCount[name] ||= 0;
itemCount[name] += 1;
}
console.log("unique values", Object.keys(itemCount));
console.log("itemCount", itemCount);
||= is a fairly new operator, if you are not using a transpiler (like Babel) to support older browsers you might want to use the following instead:
if (!itemCount[name]) itemCount[name] = 0;
Note that when using objects the all keys are converted to strings. So "1" and 1 are considered the same. If you want to differentiate between strings, numbers, complex objects (by identity, not value), etc. use a Map instead.
const itemsName = ["aaa", "bbb", "aaa", "ccc", "ddd", "ddd", "1", 1];
const itemCount = new Map();
for (const name of itemsName) {
if (!itemCount.has(name)) itemCount.set(name, 0);
itemCount.set(name, itemCount.get(name) + 1);
}
console.log("unique values", Array.from(itemCount.keys()));
for (const [name, count] of itemCount) {
console.log(typeof name, name, count);
}
I am trying to push array a value until it reach the length of 3. I want also add delay to the loop. Any suggestion to fix the code. If the condition is met, break and go to next function. I am greatly appreciate it!
let array = [];
let eachEverySeconds = 1;
//function fetchCoinPrice(params) { //BinanceUS Fee: 0.00075 or 0.075%
function Firstloop() {
for (x = 0; x < 4; x++) {
setTimeout(function() {
function fetchCoinPrice() {
binance.prices(function(error, ticker) {
//array.push(ticker.BNBBTC);
//while(array.length<3){
//if (array.length<4){
array.push(ticker.BNBBTC);
console.log("1", array);
//}else {}//if (array.length === 3) { break; }
// array.shift();
});
}
}, 1000)
}
}
// setInterval(Firstloop, eachEverySeconds * 1000);
Firstloop()
You will need to save the interval into a variable that you can then use clearInterval() on.
Here's a mockup of what you're trying to accomplish.
var array = [];
var maxLength = 3;
var delay = 250; //I shortened your delay
var ticker = {}; //I'll use this to simulate your ticker object
var looper = setInterval(function() {
ticker.BNBBTC = Math.random(); //populating your ticker property w/random value
if (array.length < maxLength) {
array.push(ticker.BNBBTC);
} else {
console.log("Stopping the looper.");
clearInterval(looper);
console.log("Here are the contents of array");
console.log(array);
}
}, delay);
I'm not sure if I've understood your purpose as there are many commented codes there but if you want to run a function for three times and run it again after a second with new prices or ... may be this code helps you:
let array = [];
let eachEverySeconds = 1;
const loopArray = (array) => {
setTimeout(async () => {
if (array.length === 3) return;
let price = Math.random() * 10;
array.push(price);
await loopArray(array);
}, 1000 * eachEverySeconds);
console.log(array);
};
loopArray(array);
I have a button addToCart, the value of that gets stored in Localstorage.
I want to update all the incoming values of localstorage, if it satisfies a certain condition.
Here is the function
addToCart(itemValue) {
console.log("cart value--", itemValue);
// this.cartProduct = this.getCartProduct(itemValue.productAlias);
let count = 0;
var countValue: any;
let shipPrice = 4.75;
let result: any = [];
// console.log("cart data", this.getCartProduct(itemValue.productAlias));
var item = {
userId: this.userId,
productid: itemValue.productId,
seller: itemValue.seller,
price: itemValue.price,
sellerId: itemValue.sellerId,
productAlias: itemValue.productAlias,
productImage: itemValue.productImage,
productName: itemValue.proName,
shippingPrice: shipPrice
};
if (count > 0) {
console.log("if condition", count);
shipPrice = 1.50;
}
// console.log("cart value--", item);
if (localStorage.getItem('cart') == null) {
this.cart.push(JSON.stringify(item));
localStorage.setItem('cart', JSON.stringify(this.cart));
// console.log(localStorage.getItem('cart'));
} else {
let cart: any = JSON.parse(localStorage.getItem('cart'));
let index: number = -1;
// let item = JSON.parse(cart);
console.log("item************" + cart);
for (var i = 0; i < cart.length; i++) {
let item = JSON.parse(cart[i]);
console.log("local storage value", item);
if (item.productid == itemValue.productId && item.seller == itemValue.seller) {
index = i;
break;
}
if (item.sellerId == itemValue.sellerId) {
count++;
console.log("count-----" + count);
let item = JSON.parse(cart[i]);
item.shippingPrice = 1.50;
cart[i] = JSON.stringify(item);
localStorage.setItem("cart", JSON.stringify(cart));
}
}
if (index == -1) {
// count=0;
cart.push(JSON.stringify(item));
localStorage.setItem('cart', JSON.stringify(cart));
}
}
// let cartValue: any = JSON.parse(localStorage.getItem('cart'));
// console.log("cart value********", cartValue);
this.helperSvc.notifySuccess('Product Added to Cart');
this.router.navigate([`/in/product/${this.pTitle}`]);
}
I want that if sellerId is same, the value of shipping price will be 1.50; and if any entry has same sellerid the shipping price will be 1.50,
and for every entry in localstorage the condition must be checked.
here is the local storage cart
{"userId":"8","productid":"1","seller":"user","price":"100","sellerId":"2","productAlias":"pure-mens-plain-shirt","productImage":"uploads/1562685351.jpg","productName":"Pure Mens Plain Shirt","shippingPrice":4.75},{"userId":"8","productid":"2","seller":"user","price":"50","sellerId":"2","productAlias":"mens-cotton-shirt","productImage":"uploads/1562685440.jpg","productName":"Mens Cotton Shirt","shippingPrice":4.75}
i want that is any entry in local storage is there and there sellerid are same, the shipping price of same sellerid should be updated to 1.50.
I have still not completely understood your question. But I think you want to check if a particular sellerId is present in your JSON array which you get from local storage. So first lets first get the data from localStorage:
const localStorageValue = localStorage.getItem(yourLocalStorageVar)
You will get the JSON array now you need to parse it and check if entry is there
const isSameSellerId = JSON.parse(localStorageValue).some(x => x.sellerId === yourSellerId)
I have used some to check if any particular object in your array has the same sellerId.
Now you can do whatever you want to do based on isSameSellerId.
I got an array with some objects. Each object has an id. So when generating a new id, I want to check if an object with this id already exists. If there is an equal id, a new one should be generated.
generateId() {
var records = store.getRecords(); // get all the objects
var newId = getNewId(); // calculate a new id
if (record.id == newId) // id already exists // record.id = id of the object
newId = generateId(); // generate a new id
else
return newId; // return the id
}
getNewId() {
// generate Id...
}
So how can I check all my records here if (record.id == newId) ? I use JQuery.
You can use a simple for loop for simlicity, it might not be efficient if you've got a lot of records obtained. If the structure of the object is the same for all records and assuming the data type of the object value matches the newId variable, this function will serve the purpose.
function DoesExist() {
for(var i = 0; i < records.length; i++) {
if(records[i].id == newId)
return true;
}
return false;
}
The way I would go about it is to split my logic into multiple functions, so that I can check any new id against the existing ones. Then, wrapping this inside a loop, I could check generated values until one is found that is not in the array. For example (methods and values added for testing):
function generateId() {
var records = store.getRecords(); // get all the objects
var newId;
var isUnique = false;
while (!isUnique) { // check if unique, repeatedly
newId = getNewId(); // calculate a new id
isUnique = checkId(newId);
}
return newId; // return the id (is unique)
}
// Check if the id is unique against existing records
function checkId(newId) {
var records = store.getRecords();
for (var key in records)
if (records[key].id == newId)
return false;
return true;
}
// Added for testing
function getNewId() {
return Math.round(Math.random() * 10);
}
var store = {getRecords: function() {return [{id: 1}, {id: 2}, {id: 4}, {id: 6}];}}
// Actual testing
console.log(generateId());
this should work as incremental id generator:
const data = [{id: 1}, {id: 2}, {id: 3}, {id: 4}, {id: 5}, {id: 6}];
const exists = id => data.some(o => o.id === id);
const newId = (start = 0) => {
const id = ++start;
return exists(id) ? newId(id) : id;
};
// you can also evaluate to implement some uid logic...
// there isn't much you can do on the client, but,
// this could also help
const newUID = () => {
const uid = Math.random().toString(32).substr(2);
return exists(uid) ? newUID() : uid;
}
console.log({
incrementalID: newId(),
UID: newUID()
});