Javascript两个数组:第一计数,第二值

58wvjzkj  于 2023-06-20  发布在  Java
关注(0)|答案(4)|浏览(84)

我有两个数组,它们都有相同的大小,看起来像这样:
a= [ 1, 2, 3, 2]b = ['this', 'is', 'my', 'good example']
数组a [i]定义了b [i]的值写入新数组的频率。对于我的例子,结果将是c = ['this', 'is', 'is', 'my', 'my', 'my', 'good example', 'good example']
我尝试了String.repeat,但我不知道如何将其导入数组

vjhs03f7

vjhs03f71#

我想这个解决办法会适合你

const a = [1, 2, 3, 2];
const b = ['this', 'is', 'my', 'good example'];

const c = a.flatMap((count, i) => Array(count).fill(b[i]));

console.log(c);
xqnpmsa8

xqnpmsa82#

你可以在另一个循环中做一个循环来实现

const a = [1, 2, 3, 2];
const b = ['this', 'is', 'my', 'good example'];

let array = [];
b.forEach((x, i) => {
  for (let j = 0; j < a[i]; j++) {
    array.push(x);
  }
})

console.log(array)
rqenqsqc

rqenqsqc3#

const a = [1, 2, 3],
      b = ['a','b','c']

console.log(
  b.reduce((acc, item, idx) => acc.concat(Array(a[idx]).fill(item)), [])
)

// or the opposite

console.log(
  a.reduce((acc, item, idx) => acc.concat(Array(item).fill(b[idx])), [])
)

我同意flatMap是完成这项任务的理想选择,@lvjonok对此做出了回答

rkue9o1l

rkue9o1l4#

您可以使用Array#reduce方法,如下所示:

const
      a = [ 1, 2, 3, 2],
      b = ['this', 'is', 'my', 'good example'],
      
      c = a.reduce(
          (acc,cur,i) => [ ...acc, ...Array(cur).fill( b[i] ) ], []
      );
      
console.log( c );

相关问题