I need help creating a function that gonna return me 3 elements from an array each time with time interval of 3 seconds.
Let say I have an array
const Array = [{name:'A'},{name:'B'},{name:'C'},{name:'D'},{name:'E'},{name:'F'},{name:'G'},{name:'H'},{name:'I'}];
It should return array like
[{name:'A'},{name:'B'},{name:'C'}]
then after 3 seconds it should return array
[{name:'D'},{name:'E'},{name:'F'}]
And so on also when the arrays gets end repeat the loop again.
I tried using chunk where i used slice and filter but that just return me an array of chunks together.
Thanks so much
You can do this with a generator:
// Takes an array and the of the slice/subarray
function* subArray(array, size) {
let i = 0;
let remaining = true;
while (remaining) {
yield array.slice(i, i + size);
i += size;
if (i >= array.length) {
remaining = false;
}
}
}
// Takes an array, a subarray size, and an interval in seconds
const getSubArraysAtInterval = (array, size, seconds) => {
const iter = subArray(array, size);
const interval = setInterval(() => {
const next = iter.next();
if (next.done) {
clearInterval(interval);
console.log('No values remaining');
} else {
console.log(next.value);
}
}, seconds * 1000)
}
getSubArraysAtInterval([1, 2, 3, 4, 5, 6], 3, 3);
Working fiddle: https://jsfiddle.net/adrice727/msx3sf03/1/
const array = [{name:'A'},{name:'B'},{name:'C'},{name:'D'},{name:'E'},
{name:'F'},{name:'G'},{name:'H'},{name:'I'}];
let i = 0
setInterval(() => {
console.log(array.slice(i,i+3))
i*3 > array.length ? i=0 : i += 3
}, 3000)
The jsbin: https://jsbin.com/yoqelu/edit?html,js,console,output
Related
How to return an array with the step of the sum of the previous value?
I have an input number that is 1000
I want to get [1000, 2000, 3000 ... 10000]
I'm trying to:
const range = (i: number, o: number) => {
const arr = [0, 1, 2, 3, 4].reduce(
(accumulator: any, currentValue: any, index: any, array: any) => {
console.log((array[index] = accumulator + currentValue));
return 1;
},
10000
);
};
range(1000, 10000);
Use Array.from and provide the first argument as an object with length property that is equal to the step, and second argument as mapping function that simply multiply the index and step:
const range = (start,end) =>
Array.from( {length: end/start} ,(_,i) => (i+1) * start )
console.log(range(1000,10000))
Try this:
function range(start, end) {
var arr = []; // Start with an empty array
/* Start a counter at the start value, and increment it
* by the start value while it is less than or equal to
* the end value. Push this value into arr each time
*/
for (let i = start; i <= end; i += start) {
arr.push(i);
}
return arr; // Return the array
}
Use simple loop and check if number * index <= max while adding values to new array:
const range = (number, max) => {
let index = 1;
let newArray = [];
do {
newArray.push(number * index);
index++;
} while (number * index <= max);
return newArray;
};
console.log(range(1000, 10000));
console.log(range(10000, 10000));
const range = (start, end) => {
let acc = [];
for (let i = start; i <= end; i = i + start) {
acc = [...acc, i];
}
return acc;
}
If not, please elaborate your example to clearly state the intent of ...step of the sum of the previous value.
let numbers = [2, 2, 6, 10];
const findAvarage = (numbers) => {
let total = 0;
let checkIntegers = numbers.every(i => !Number.isInteger(i))
if (checkIntegers = true) {
for(let i = 0; i < numbers.length; i++) {
total += numbers[i];
}
let avg = total / numbers.length;
return avg
} else {
return "Only integers allowed"
}
const compareNumbers = (numbers) => {
}
In this code I calculate the avarage of the given numbers in array and now I want to find how many numbers in array are greater that avarage number with second function
I tried to use find method but it did not work out,any solutions on this please?
You can use filter function to filter out the numbers that are larger than average.
const avg = findAvarage(numbers)
const count = numbers.filter(number => number > avg).length
const compareNumbers = (numbers) => {
const avg = findAvarage(numbers);
let greater = 0;
numbers.forEach((num) => { if (num > avg) greater++; });
return greater;
}
u can use filter or reduce to solve it
let numbers = [2, 2, 6, 10];
function countNumbers(number){
return numbers.filter(num=> num>=number).length;
}
function countNumbers2(number){
return numbers.reduce((count,item)=>count+(item>=number),0)
}
console.log(countNumbers(7));
console.log(countNumbers2(3))
Javascript does not provide many extension methods that can be used for arrays, you have just some basics operations.
Your code can be more cleaner if you turn this need into extensions for arrays that you can them every where without calling functions, you can do as follow:
Object.defineProperties(Array.prototype, {
count: {
value: function(value) {
if(isNan(value)) return NaN;
return this.filter(x => x>=value).length;
}
},
average:{
value:function(){
let total = 0;
if(!this.every(i => Number.isInteger(i)))
return NaN;
for(let i = 0; i < numbers.length; i++) {
total += numbers[i];
}
return total/this.length;
}
}
});
and you can use it like this for you example
var result = numbers.count(numbers.average())
this way ?
const findAvarage=(a,b,c,d) => [a,b,c,d].reduceRight((t,n,i,a)=>
{
t += n
if (!i) t /= a.length
return t
},0)
, greaterOrEqualCount = (a,b,c,d) =>
{
let avg = findAvarage(a,b,c,d)
return [a,b,c,d].reduce((r,n)=>r+(n<avg?0:1),0)
}
console.log("count ",greaterOrEqualCount(2,2,6,10))
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);
My program should be as following:
Input : {1,2,3,2,1,8,-3}, sum = 5
Output should be 3 example combinations ({2,3}, {3,2}, {8,-3}) have sum
exactly equal to 5.
I tried to do it in JavaScript but I'm confused.
function findSubarraySum(arr, sum) {
var res = 0;
var currentSum = 0;
for (var i = 0; i < arr.length; i++) {
currentSum += arr[i];
if (currentSum == sum)
res++;
}
return res;
}
console.log(findSubarraySum([1, 2, 3, 4], 10));
You first need a way to iterate over all the unique ways you can choose a start and and of your subarray boundaries (your slice definition).
In my code below, I use a combinations function to get all possible combinations of two indexes for the array supplied. You could do something else, like a simple doubly nested for loop.
Next you need to take the slice of the array according to the slice definition and reduce the elements into a sum. The Array.prototype.reduce function works well for that.
Finally, you want to include the subArray in the list of results only if the reduced sum matched the desired sum.
// Input : {1,2,3,2,1,8,-3}, sum = 5
const { combinations, range } = (() => {
const _combinations = function*(array, count, start, result) {
if (count <= 0) {
yield [...result]; // Yes, we want to return a copy
return;
}
const nextCount = count - 1;
const end = array.length - nextCount; // leave room on the array for the next remaining elements
for (let i = start; i < end; i += 1) {
// we have already used the element at (start - 1)
result[result.length - count] = array[i];
const nextStart = i + 1; // Always choose the next element from the ones following the last chosen element
yield* _combinations(array, nextCount, nextStart, result);
}
};
function* combinations(array, count) {
yield* _combinations(array, count, 0, Array(count));
}
function* range(l) {
for (let i = 0; i < l; i += 1) {
yield i;
}
}
return {
combinations,
range,
};
})();
const subArraysBy = (predicate, array) => {
const result = [];
for (const [beg, end] of combinations([...range(array.length+1)], 2)) {
const subArray = array.slice(beg, end);
if (predicate(subArray)) {
result.push(subArray);
}
}
return result;
};
const sum = array => array.reduce((sum, e) => sum + e);
console.log(
subArraysBy(
a => sum(a) === 5,
[1, 2, 3, 2, 1, 8, -3],
),
);
References:
MDN: Array.prototype.reduce
MDN: function* -- not required for your solution
Lodash: _.range -- implemented this in my code rather than use the lodash one. They work similarly.
Python Docs: combinations - My combinations implementation is inspired by python itertools.
I have homework to write a function that will be called with 2 parameters:
a is a list of numbers.
amount represents the count of the numbers in the array.
The function should return the number in the list that occurs amount times.
For example , if a = [5,5,5,3,2,1,1], and amount = 2, the function should return 1, because there are only two ones in the array. If amount = 3, the function should return 5 , if amount = 6, the function will return 0 since there are numbers that occur six time.
try this one
var max=3;
var array=[5,5,5,3,2,1,1];
console.log(verify(array,max))
function verify(array,max) {
var match=0;
array.map(obj => {
if(array.filter(x => x === obj).length == max)
match= obj;
});
return match;
}
Here is a way to get the values by count using reduce.
Since there may be more than one element matching the count, or even 0, an array is returned.
reduce is used to build a map (object) of the unique items to their counts. We the find the map entries where the counts match, and the keys (unique items) for these entries are returned.
const count = (arr, num) => {
const count = arr.reduce((count, x) => {
count[x] = (count[x] || 0) + 1;
return count;
}, {});
return Object.entries(count)
.filter(([k, v]) => v === num)
.map(([k, v]) => +k);
}
console.log(count([5,5,5,3,2,1,1], 1)); // [2, 3]
console.log(count([5,5,5,3,2,1,1], 3)); // [5]
console.log(count([5,5,5,3,2,1,1], 5)); // []
make a array of unique values from real array. Then loop though it and filter() real array to check the count of elements.
const array = [5,5,5,3,2,1,1]
function count(arr,amount){
const unique = [...new Set(arr)];
for(let item of unique){
if(arr.filter(num => num === item).length === amount)
return item;
}
return 0;
}
console.log(count(array,1));
console.log(count(array,2));
console.log(count(array,3));
console.log(count(array,4));
console.log(count(array,5));
You should use below code.
#RaviTeja's code is giving max number of array but you dont want it. You want to number which is same quantity with your "amount" parameter.This code provides this for you
function findingAmount() {
var numberContainer = [ 2, 3, 2,5,2,3 ];
console.log(findingAmountImp(numberContainer,1)); // result 5
console.log(findingAmountImp(numberContainer,2)); // result 3
console.log(findingAmountImp(numberContainer,3)); // result 2
}
function findingAmountImp(numbers,amount) {
var count=1;
for (i=0; i<numbers.length; i++) {
for (j=0; j<numbers.length; j++) {
if(i===j){
j=j+1;
if(j<numbers.length){
if(numbers[i] === numbers[j])
{
count++;
}
}else{
for(k=0;k<i;k++){
if(numbers[i] === numbers[k])
{
count++;
}
}
}
}else{
if(numbers[i] === numbers[j])
{
count++;
}
}
}
if( count === amount){
return numbers[i]
}
count=1;
}
}