首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将数组的元素乘以3个权重因子,然后重复

将数组的元素乘以3个权重因子,然后重复
EN

Stack Overflow用户
提问于 2021-01-19 16:23:37
回答 3查看 63关注 0票数 0

我希望能够将每个数组元素乘以3个不同的权重因子。

用户输入= [24,3,0, 56,43,34]

输出= 24x7,3x3,0x1 + 56x7, 43x3, 34x0..基本上,在数组的每3个元素上重复7的乘法,然后是3,然后是0。

它看起来像这样:

对于每个数组元素,将每个数组权重因子相乘,当达到第三个元素时重复此操作

代码语言:javascript
复制
function multiplyWeightFact(input){

 const weighting = [7,3,1]

  for (let i = 0; i < input.length ; i++) {
    console.log( input[0] * weighting[0])
    console.log( input[1] * weighting[1])
    console.log( input[3] * weighting[2])
    break
}
for (let index = 0; index < input.length; index++) {
  console.log( input[4] * weighting[0])
  console.log( input[5] * weighting[1])
  console.log( input[6] * weighting[2])
  break 
}
  }

来自用户的输入= [24,3,0, 56,43,34]

如果我们有一个数组,假设有100个数字,它就会继续。

输出需要如下所示:

resultOutput = 374 when input is [24,10]

当然,上面的功能是不可持续的,所以有没有更好的方法呢?

EN

回答 3

Stack Overflow用户

发布于 2021-01-19 16:30:33

您可以通过获取一个索引和长度为weighting的余数运算符进行映射。

代码语言:javascript
复制
const
    multiplyBy = weighting => (v, i) => v * weighting[i % weighting.length],
    array = [24, 3, 0, 56, 43, 34],
    weighting = [7, 3, 1],
    result = array.map(multiplyBy(weighting));

console.log(...result);

使用x

代码语言:javascript
复制
const
    multiplyBy = weighting => (v, i) => `${v}x${weighting[i % weighting.length]}`,
    array = [24, 3, 0, 56, 43, 34],
    weighting = [7, 3, 1],
    result = array.map(multiplyBy(weighting));

console.log(...result);

票数 2
EN

Stack Overflow用户

发布于 2021-01-19 16:27:10

您可以遍历数组元素,并使用模运算符根据右因数的位置与之相乘。

模数解释

计算余数。

代码语言:javascript
复制
const weighting = [7, 3, 1] // Instead of 3 weighting.length

1. 0 % 3 = 0 = Array Element = 7
2. 1 % 3 = 1 = Array Element = 3
3. 2 % 3 = 2 = Array Element = 1
4. 3 % 3 = 0 = Array Element = 7

And again ...

代码语言:javascript
复制
function multiplyWeightFact(input) {

  const weighting = [7, 3, 1]


  for (let index = 0; index < input.length; index++) {

    input[index] *= weighting[index % weighting.length];


  }
  return input;
}
let input = [5,4,3,2,1]

console.log(multiplyWeightFact(input));

票数 0
EN

Stack Overflow用户

发布于 2021-01-19 16:33:38

您可以只对输入进行map操作,然后根据其索引将其乘以权重。然后,我们可以使用remainder operator将索引保持在权重数组的范围内。

代码语言:javascript
复制
function multiplyWeightFact(input, weight){  
  return input.map((num, index) => num * weight[index % weight.length]);
}

const weight = [7, 3, 0];
const input = [24, 3, 0, 56, 43, 34];

const result = multiplyWeightFact(input, weight);

console.log(result);

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65787732

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档