如何在给定一组值的情况下找到数组中剩余的 % 值?

时间:2021-06-25 07:27:22

标签: javascript arrays

考虑我们有一个对象数组:

let online = [{start:4,end:8},{start:19,end:34},{start:65,end:80}];

我想从这个数据推断另一个数组:

let offline = [{start:0,end:3},{start:9,end:18},{start:35,end:64},{start:81,end:100}];

最大数量可以是 100,最小可以是 0。

3 个答案:

答案 0 :(得分:0)

添加一些自定义逻辑,如下所示。我还添加了一个排序函数,只是为了保证数组中元素的顺序。

let online = [
  { start: 4, end: 8 },
  { start: 19, end: 34 },
  { start: 65, end: 80 },
];
const onlineSort = online.sort((a, b) => a.start - b.start);
let currentIndex = onlineSort[0].start < 0 ? onlineSort[0].start < 0 : 0;
const offLine = [];
onlineSort.forEach((node) => {
  offLine.push({
    start: currentIndex,
    end: node['start'] - 1
  });
  currentIndex = node['end'] + 1;
});
console.log(online);
console.log(offLine);

答案 1 :(得分:0)

试试这个

let online = [
  { start: 4, end: 8 },
  { start: 19, end: 34 },
  { start: 65, end: 80 },
];

let _start = 0;
const result = [];
online.forEach((on) => {
  const { start, end } = on;
  if (_start !== start) {
    result.push({
      start: _start,
      end: start - 1,
    });
  }
  _start = end + 1;
});
if (_start < 100) {
  result.push({
    start: _start,
    end: 100,
  });
}

console.log(result);

答案 2 :(得分:0)

这是一种利用reduce(和在线数组)来累积离线范围的方法。

这里展开了。这是代码段中的单行

let offline = online.reduce((b, a, i) => 
   // set up our reducer and include the index i
   [...b, {start: online[i].end + 1, end: i < online.length - 1 ? online[i + 1].start - 1 : 100}], 
   // return a spread of the current accumulating array b, along with the next object, that gets it's start and end values from the online array using the same index
   [{start: 0, end: online[0].start - 1}]);
   // start off our array with the first set of values.
   .filter(f=>f.end>0)
   // incase the online array starts at zero, this will remove and invalid entries

const getOffline = (online) =>  online.reduce((b, a, i) => [...b, {start: online[i].end + 1, end: i < online.length - 1 ? online[i + 1].start - 1 : 100}], [{start: 0, end: online[0].start - 1}]).filter(f=>f.end>0);

console.log(getOffline([{start:4,end:8},{start:19,end:34},{start:65,end:80}]))
console.log(getOffline([{start:0,end:8},{start:19,end:34},{start:65,end:80}]))

相关问题