0

I have an array which looks like this

Array[20]
0 : "2"
1 : "3"
2 : "4"
3 : "5"
4 : "6"
5 : "7"
6 : "8"
7 : "9"
8 : "10"
9 : "11"
10: "12"
11: "13"
12: "14"
13: "15"
14: "16"
15: "17"
16: "18"
17: "19"
18: "20"
19: "12"

Now I want to create arrays after every 4th occurrence like this

First Array

0 : "2"
1 : "6"
2 : "10"
3 : "14"
4 : "18"

Second Array

0 : "3"
1 : "7"
2 : "11"
3 : "15"
4 : "19"

and so on...

Yet I have written this code

for (var i = 0; i < $scope.data.effort.length; i = i+ 4) {
    efforts.push( $scope.data.effort[i]);
 };

From above code I am getting only first array what should I need to do to get remaining arrays. Please help

2 Answers 2

2

All you need is to run an extra loop outside that which handles your starting index. LIke this:

efforts = []
for (var j = 0; j < arr.length / 4; j++) {
  efforts[j] = []
  for (var i = j; i < arr.length; i = i + 4) {
    efforts[j].push(arr[i]);
  };
  console.log(efforts[j])
}

Here's working example: (simplified in JS, without $scope and all)

var arr = [
  "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14",
  "15", "16", "17", "18", "19", "20", "12"
]
efforts = []
for (var j = 0; j < arr.length / 4; j++) {
  efforts[j] = []
  for (var i = j; i < arr.length; i = i + 4) {
    efforts[j].push(arr[i]);
  };
  console.log(efforts[j])
}

Or, interestingly, you can use the beast, I mean, reduce to achieve the same. :)

var arr = [
  "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14",
  "15", "16", "17", "18", "19", "20", "12"
]
efforts = arr.reduce(function(arr, cur, curIndex) {
  arr[curIndex % 4] = arr[curIndex % 4] || [];
  arr[curIndex % 4].push(cur);
  return arr
}, [])
console.log(efforts)

Sign up to request clarification or add additional context in comments.

3 Comments

@Ramkishan glad I could help :)
Let me try this
Yes it is really interesting from the first one. once again thanks.
1

Another simple way with array filter:

var originalArray =["2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21"];           
var firstArray = originalArray.filter((el, index) => (index%4 === 0));
var secondArray = originalArray.filter((el, index) => (index%4 === 1));

and so on

Comments

Your Answer

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.