简体   繁体   中英

how to push a count into 1D array to make it 2D

I want to create a 1D array into 2D.

I have an array arr1 which is 1D

Now I am searching the elements of this 1D array arr1 into another array arr2 which contains the search variables. I am successfully able to count the occurrence of arr1 from arr2, but unable to store the count in arr1.

arr2 = [a,a,a,a,b,d,e,f,f,f,g,g....]

var arr1 = ["a","b","c".......]

  for (i =0; i<shrink_days.length; i++){
    var count = arr2.flat().reduce(function(n, val) {
    return n + (val === arr1[i]);
}, 0);
  //arr1[i][1].push(count)
}

my arr1[i].push(count) gives error 'arr1[i][1].push is not a function'.

What I want to achieve is: arr1 = [[a,4],[b,1],[c,0],[d,1],[e,1],[f,3],[g,2]......]

You can replace the element of the first array with a new array containing the original element and the count:

arr1[i] = [arr1[i], count]

Arguably, if you care about immutability, you should leave arr1 untouched and create a third array with that structure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM