JavaScript数字数组的均等分割方法详解

2023年11月24日14:56:54

如果我们可以将一个数组分为一个元素和其余元素,则我们需要编写一个返回true的函数,以使该一个元素等于除自身之外的所有其他元素的乘积,否则返回false。

例如:如果数组是-

const arr = [1, 56, 2, 4, 7];

那么输出应该为真

因为56等于-

2 * 4 * 7 * 1

示例

以下是代码-

const arr = [1, 56, 2, 4, 7];
const isEqualPartition = arr => {
   const creds = arr.reduce((acc, val) => {
      let { prod, max } = acc;
      if(val > max || !max){
         prod *= (max || 1);
         max = val;
      }else{
         prod *= val;
      }
      return { prod, max };
   }, {
      prod: 1,
      max: null
   });
   return creds.max === creds.prod;
};
console.log(isEqualPartition(arr));

输出结果

以下是控制台中的输出-

true

  • 更新时间:2023年11月24日14:56:54 ,共 561 字。