Split Array into Sub-Arrays Based on Value

Split array into sub-arrays based on value

I tried golfing it a bit, still not a single method though:

(1..9).chunk{|i|i%3==0}.reject{|sep,ans| sep}.map{|sep,ans| ans}

Or faster:

(1..9).chunk{|i|i%3==0 || nil}.map{|sep,ans| sep&&ans}.compact

Also, Enumerable#chunk seems to be Ruby 1.9+, but it is very close to what you want.

For example, the raw output would be:

(1..9).chunk{ |i|i%3==0 }.to_a                                       
=> [[false, [1, 2]], [true, [3]], [false, [4, 5]], [true, [6]], [false, [7, 8]], [true, [9]]]

(The to_a is to make irb print something nice, since chunk gives you an enumerator rather than an Array)


Edit: Note that the above elegant solutions are 2-3x slower than the fastest implementation:

module Enumerable
def split_by
result = [a=[]]
each{ |o| yield(o) ? (result << a=[]) : (a << o) }
result.pop if a.empty?
result
end
end

how to split a numpy array into subarrays based on values of one colums

First you find all arrays which contains 2 or which do not contains 2. This array will be full with True and False values. Transform this array to an array with zeros and ones. Check where there are differences (like [0, 0, 1, 1, 0] will be: 0, 1, 0, -1.

Based on the change one can use numpy where to find the indices of those values.

Insert the index 0 and the last index for the big array, so you are able to zip them in a left and right slice.

import numpy as np
big_array = np.array([[0., 10., 2.],
[2., 6., 2.],
[3., 1., 7.1],
[3.3, 6., 7.8],
[4., 5., 2.],
[6., 6., 2.],
[7., 1., 2.],
[8., 5., 2.1]])
idx = [2 in array for array in big_array]
idx *= np.ones(len(idx))
slices = list(np.where(np.diff(idx) != 0)[0] + 1)
slices.insert(0,0)
slices.append(len(big_array))

result = list()
for left, right in zip(slices[:-1], slices[1:]):
result.append(big_array[left:right])

'''
[array([[ 0., 10., 2.],
[ 2., 6., 2.]]),
array([[3. , 1. , 7.1],
[3.3, 6. , 7.8]]),
array([[4., 5., 2.],
[6., 6., 2.],
[7., 1., 2.]]),
array([[8. , 5. , 2.1]])]
'''

Split the array in to sub arrays based on array key value

One way to do it with simple foreach() loop to push values based on your brand_id like below-

$key = 'brand_id';
$return = array();
foreach($array as $v) {
$return[$v[$key]][] = $v;
}
print_r($return);

WORKING DEMO: https://3v4l.org/bHuWV

Split a NumPy array into subarrays according to the values (not sorted, but grouped) of another array

One way to solve this is to build up a list of filter indexes for each y value and then simply select those elements of x. For example:

z_0 = x[[i for i, v in enumerate(y) if v == 0]]
z_1 = x[[i for i, v in enumerate(y) if v == 1]]
z_2 = x[[i for i, v in enumerate(y) if v == 2]]

Output

array([[ 1,  2,  8],
[ 2, 9, 1],
[ 4, 3, 5],
[10, 2, 3],
[11, 2, 4]])
array([[3, 8, 9],
[5, 2, 3],
[6, 4, 7]])
array([[7, 2, 3],
[8, 2, 2],
[9, 5, 3]])

If you want to be more generic and support different sets of numbers in y, you could use a comprehension to produce a list of arrays e.g.

z = [x[[i for i, v in enumerate(y) if v == m]] for m in set(y)]

Output:

[array([[ 1,  2,  8],
[ 2, 9, 1],
[ 4, 3, 5],
[10, 2, 3],
[11, 2, 4]]),
array([[3, 8, 9],
[5, 2, 3],
[6, 4, 7]]),
array([[7, 2, 3],
[8, 2, 2],
[9, 5, 3]])]

If y is also an np.array and the same length as x you can simplify this to use boolean indexing:

z = [x[y==m] for m in set(y)]

Output is the same as above.

Iteratively split an array to subarrays according to a given length

It seems you want to create all subarrays of a given length from an array.

You can do it by hand:

static double[][] subArrays(double[] arr, int k)
{
double[][] subArrs = new double[arr.length-k+1][k];

for(int i=0; i<subArrs.length; i++)
for(int j=0; j<k; j++)
subArrs[i][j] = arr[i+j];

return subArrs;
}

Or use the built-in method Arrays.copyOfRange:

static double[][] subArrays(double[] arr, int k)
{
double[][] subArrs = new double[arr.length-k+1][];

for(int i=0; i<subArrs.length; i++)
subArrs[i] = Arrays.copyOfRange(arr, i, i+k);

return subArrs;
}

Test:

double[] arr = {2, 4, 6, 30, 9};

for(double[] subArr : subArrays(arr, 3))
System.out.println(Arrays.toString(subArr));

Output:

[2.0, 4.0, 6.0]
[4.0, 6.0, 30.0]
[6.0, 30.0, 9.0]

Dynamically split an array into subarrays

This really isn't a question of React (or where-ever useEffect comes from). This is really a general Javascript question, and it's a problem that suits itself well for solving with functional programming, or at least, with one of the staples of functional programming: reduce

In this case, you could supply the 2nd argument which is the initial value of the accumulator -- in this example an empty object works well. You can choose any key from the data to bucket the results:

// Choose a key that each object in the set has, e.g. 'fromuserid' or 'touserid'
const group_by = 'fromuserid';

let bucketed = giftcards.reduce(function (acc, x) {
let pivot = x[group_by]
let current_vals = (acc.hasOwnProperty(pivot) ? acc[pivot] : []);
current_vals.push(x);
acc[pivot] = current_vals;
return acc
}, {});

console.log(bucketed);

If you really needed to land on the second data structure you shared, you could jostle your initialValue and the exact placement of values into the accumulator, but hopefully this demonstrate the concept of how to dynamically choose how to group the data.

Java: Split array by value

As it was correctly mentioned in the comment you haven't provided definition of the slope in your code. So it's not completely clear what your code is doing.

However, this is just one of the possible ways to do it if I understood you correctly:

public int[][] splitByValue(final int[] arr) {
Map<Integer, Integer> map = new HashMap<>();
for (int number : arr) {
map.put(number, map.getOrDefault(number, 0) + 1);
}
int[][] result = new int[map.keySet().size()][];
int i = 0;
for (Integer key : map.keySet()) {
result[i] = new int[map.get(key)];
for (int j = 0; j < result[i].length; j++) {
result[i][j] = key;
}
i++;
}
return result;
}

The assumption here is that you are only dealing with array of integers.

Split array into subarray based on keys

Can you try the below code

<?php

$input = array(
'1' => array(
'0'=> array(
'service_id' => 1,
'service_name'=>'lorem'
),
'1'=> array(
'service_id' => 1,
'service_name'=>'ipsum'
),
),
'2' => array(
'0'=> array(
'service_id' => 1,
'service_name'=>'lorem'
),
'1'=> array(
'service_id' => 1,
'service_name'=>'ipsum'
),
),
);

foreach($input as $key => $val){
${"array".$key} = $val;// Create variables with name $array1,$array2...

}

foreach($input as $key => $val){
// Will print in loop as array1 array2....
echo '<pre>'; print_r(${"array".$key}); echo '</pre>';
}

//Individual Prinitng array1
echo '<pre>'; print_r($array1); echo '</pre>';


Related Topics



Leave a reply



Submit