How to add a range of elements of an array to another array in JavaScript

2 Answers

0 votes
const source = [10, 20, 30, 40, 50, 60, 70];
let target = [1, 2, 3];
 
// Add elements from index 2 to 5 (30, 40, 50)
target.push(...source.slice(2, 5));
 
console.log(target);  
 
 
 
/*
run:
 
[ 1, 2, 3, 30, 40, 50 ]
 
*/

 



answered Oct 17 by avibootz
0 votes
const source = [10, 20, 30, 40, 50, 60, 70];
let target = [1, 2, 3];

// Add elements from index 2 to 5 (30, 40, 50)
let result = target.concat(source.slice(2, 5));

console.log(result);  



/*
run:

[ 1, 2, 3, 30, 40, 50 ]

*/

 



answered Oct 17 by avibootz
...