打字稿从数组的前面和结尾获取X个元素

时间:2019-03-08 02:52:50

标签: javascript arrays angular typescript

我想优化下面的代码,因为它似乎有太多步骤。该代码确实有效,但是我想看看是否有更好的方法。我基本上想从shippingTracings数组中获取前X个元素和后X个元素。有没有办法优化那部分?

此外,我正在基于numberOfTracings / 2派生我想要的数组左侧和右侧的元素。对于一个奇数,我正在舍入,但是您可以看到我正在使用paddingRight来使用余数(如果有)。还有更好的方法吗?

        const numberOfTracings = environment.shipmentTracingMarkerLimit - this.shipmentTracking.shipmentStops.length;  // i.e. 7
        const paddingLeft = Math.floor(numberOfTracings / 2);
        const paddingRight = numberOfTracings - paddingLeft * 2; //i am doing this because I want to use that extra array spot to be padded.  It 
        const myFirstArr = this.shipmentTracking.shipmentTracings.slice(0, paddingLeft);
        const myFirstArr2 = this.shipmentTracking.shipmentTracings.slice(-(paddingLeft + paddingRight));
        const myFirstArr3 = myFirstArr.concat(myFirstArr2);
        myFirstArr3.forEach((shipmentTracing) => this.createRouteMarkerForTracing(shipmentTracing));

1 个答案:

答案 0 :(得分:2)

使用注释中的示例,您可以使用ES2015 spread operator来执行以下操作:

const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];

const padding = 2;

const firstAndLast = [...fruits.slice(0, padding), ...fruits.slice(-padding)];

console.log(firstAndLast);

编辑:基于注释的更新,用于基于padding计算左/右切片:

const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango", "Dragon Fruit", "Kiwi", "Apricot", "Lime", "Plantain"];

const getFirstAndLast = (arr, padding) => {
  const left = Math.ceil(padding / 2);
  const right = padding - left;
  return [...arr.slice(0, left), ...arr.slice(-right)];
};

// gets first 4 and last 3 given a padding of 7
const firstAndLast = getFirstAndLast(fruits, 7);

console.log(firstAndLast);