Terse way to intersperse element between all elements in JavaScript array?

前端 未结 16 1049
终归单人心
终归单人心 2020-12-17 09:19

Say I have an array var arr = [1, 2, 3], and I want to separate each element by an element eg. var sep = \"&\", so the output is [1, \"&a

16条回答
  •  渐次进展
    2020-12-17 09:53

    export const intersperse = (array, insertSeparator) => {
      if (!isArray(array)) {
        throw new Error(`Wrong argument in intersperse function, expected array, got ${typeof array}`);
      }
    
      if (!isFunction(insertSeparator)) {
        throw new Error(`Wrong argument in intersperse function, expected function, got ${typeof insertSeparator}`);
      }
    
      return flatMap(
        array,
        (item, index) => index > 0 ? [insertSeparator(item, index), item] : [item] // eslint-disable-line no-confusing-arrow
      );
    };
    

提交回复
热议问题