0

I have a sample array, arr = [5,4,3,3,2,2,1] and i need to generate a multidimensional array like that:

 [0] => Array
    (
        [0] => 5
    )
 [1] => Array
    (
        [0] => 4
    )
 [2] => Array
    (
        [0] => 3
        [1] => 3
    )
 [3] => Array
    (
        [0] => 2
        [1] => 2
    )
 [4] => Array
    (
        [0] => 1
    )

I'm not sure about how javascript array works. I've tried to write the code but ended up the all the new array elements is 1

var arr = [5,4,3,3,2,2,1]
var arrtemp = []
var temp = []
var tempval = 0
var col = 0


for (var i=0;i<arr.length;i++){
  if (i==0) {
    temp.push(arr[i])
    tempval = arr[i]
  }
  
  else {
    if (arr[i] == tempval){
      temp.push(arr[i]);
    }
    else {
      arrtemp[col] = temp;
      col++;
      temp.length =0;
      temp.push(arr[i]);
      tempval = arr[i];
    }
  }
}

console.log(arrtemp)

4 Answers 4

1

Luckily, your arr is already sorted. I'd use reduce instead, where the accumulator is an array of arrays. If the last array in the accumulator doesn't have the same value as the new item you're iterating over, create a new array in it, and push to the last array in the accumulator:

var arr = [5,4,3,3,2,2,1];
const output = arr.reduce((a, num) => {
  if (!a.length || a[a.length - 1][0] !== num) {
    a.push([]);
  }
  a[a.length - 1].push(num);
  return a;
}, []);
console.log(output);

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

Comments

1

try this

let arr = [5,4,3,3,2,2,1];
let last;
let newArr =[];
for (var i=0;i<arr.length;i++){
  if (last!=arr[i]) {
    let temp=[];
    temp.push(arr[i]);
    newArr.push(temp);
    last =arr[i];
  }
  else
  {
    newArr[newArr.length-1].push(arr[i]);
  }
}

console.log(newArr);

Comments

1

You can .join() the array to form a string. Then on the string, you can match consecutive runs of numbers using .match() with regex. Lastly, you can .split() each match into an array.

See example below:

const arr = [5,4,3,3,2,2,1];
const str = arr.join('').match(/(.)\1*/g).map(v => v.split(''));
             
console.log(str);

If your result must be numbers you can add an additional .map() to convert each string into a number:

const arr = [5,4,3,3,2,2,1];
const str = arr.join('')
             .match(/(.)\1*/g)
             .map(v => v.split('').map(Number));
             
console.log(str);

Comments

1

let arr = [5, 4, 3, 3, 2, 2, 1];
let newArr = [[]];
let curVal = 0;
let col = 0;

curVal = arr[0];
for (let i = 0; i < arr.length; i++) {
  if (arr[i] != curVal) {
    col++;
    newArr.push([]);
    curVal = arr[i];
  }
  newArr[col].push(curVal);
}

console.log(newArr);

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.