0

I'm looking for a simple method to iterate over an array and generate a result like below... Better if someone can show me how to do this in the ES2015 way.

var numbers = ['one', 'two', 'three'];
/* Expected result */
/* 
 0: ['one', 'two', 'three'],
 1: ['one', 'two'],
 2: ['one']
*/

https://jsfiddle.net/minuwan/1eL83sbz

asked Feb 18, 2019 at 9:40
2
  • 2
    You're gonna wanna clone the array for each loop, var clone = myArray.slice(0); Commented Feb 18, 2019 at 9:43
  • jsfiddle.net/vp0f2woq Commented Feb 18, 2019 at 9:43

2 Answers 2

2

You could map the sliced array.

var numbers = ['one', 'two', 'three'],
 result = numbers.map(function (_, i, a) {
 return a.slice(0, a.length - i);
 });
console.log(result);

answered Feb 18, 2019 at 9:46
Sign up to request clarification or add additional context in comments.

Comments

2

You can use slice to get the output you want instead of using pop since it will modify your numbers array

 var numbers = ['one', 'two', 'three'];
 var array = [];
 var arrayLength = numbers.length;
 
 for (var i = 0; i < arrayLength; i++) {
 array[i] = numbers.slice(0, arrayLength - i);
 }
 
 console.log(array);

or you would simply use map with slice

var numbers = ['one', 'two', 'three']
var array = numbers.map(function (_, i) {
 return numbers.slice(0, numbers.length - i);
});
console.log(array);

answered Feb 18, 2019 at 9:43

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.