简体   繁体   中英

Javascript es6 array mapping

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM