How to Split an Array According to Conditional Statement

How to split an array according to conditional statement?

Here's something that I think does what you desire. To test it I had to create some sample input data since you don't have any in your question—which is what is going on at the very beginning of the snippet.

For each time range interval, it creates a separate "bucket" which contains the corresponding time values within the time range. Note that some time values may end up being place in two buckets since the interval ranges overlap.

from pprint import pprint
import random
random.seed(42) # Create same "random" sequence each run for testing.

# First create some test data.
INTERVAL = 0.02 # 20 ms
start = 37913
times = []

nvalues = 2, 3, 4, 2, 1 # Number of values in each interval.

for i, nvalue in enumerate(nvalues):
lowerbounds = start + i*INTERVAL
upperbounds = start + (i+1)*INTERVAL
for _ in range(nvalue):
times.append(random.uniform(lowerbounds, upperbounds))

print('There are {} time values:'.format(len(times)))
times.sort() # Put into ascending order.
pprint(times)

#=======
# Split the times up into "buckets" of values depending on their range.
HALF_INTERVAL = INTERVAL / 2
brackets = []
print()
print('Time brackets:')
st = int(min(times))
for i in range(4):
begin = round(st + i*HALF_INTERVAL, 6)
end = round(begin + INTERVAL, 6)
brackets.append((begin, end))
print(' ', begin, end)

buckets = [[] for _ in range(len(brackets))] # Create empty buckets.
for t in times: # Put each time in the cooresponding bucket of times.
for i, (begin, end) in enumerate(brackets):
if begin <= t <= end:
buckets[i].append(t)

print()
print('Stored in corresponding interval bucket:')
for i, bracket in enumerate(brackets):
print('bucket[{}]: range: {!r}, values: {}'.format(
i, bracket, buckets[i]))

Sample Output:

There are 12 time values:
[37913.0005002151,
37913.01278853597,
37913.02446421476,
37913.025500586366,
37913.03472942428,
37913.04173877665,
37913.048438436395,
37913.05353398975,
37913.05784359135,
37913.060595944386,
37913.064372759494,
37913.09010710576]

Time brackets:
37913.0 37913.02
37913.01 37913.03
37913.02 37913.04
37913.03 37913.05

Stored in corresponding interval bucket:
bucket[0]: range: (37913.0, 37913.02), values: [37913.0005002151, 37913.01278853597]
bucket[1]: range: (37913.01, 37913.03), values: [37913.01278853597, 37913.02446421476, 37913.025500586366]
bucket[2]: range: (37913.02, 37913.04), values: [37913.02446421476, 37913.025500586366, 37913.03472942428]
bucket[3]: range: (37913.03, 37913.05), values: [37913.03472942428, 37913.04173877665, 37913.048438436395]

Split array with condition on element

You could create a map, keyed by dates, and with as value an empty array. Then populate those arrays. Finally extract the arrays that have more than one element, and add to that result a combined array of those single-element arrays:

function group(data) {
let map = new Map(data.map(o => [o.date, []]));
for (let o of data) map.get(o.date).push(o);
return [
...[...map.values()].filter(({length}) => length > 1),
[...map.values()].filter(({length}) => length == 1).flat()
];
}

let data = [{"date":"2021-07-07"},{"date":"2021-07-07"},{"date":"2021-07-07"},{"date":"2021-07-08"},{"date":"2021-07-09"},{"date":"2021-07-10"},{"date":"2021-07-10"}];

console.log(group(data));

split an array into two based on condition using javascript

You could take an array and push the objects according their availability with a single loop.

const
data = [{ product_id: 4, product_name: "Samsung", category_name: "Tv and home appliance", is_Available: 1 }, { product_id: 8, product_name: "Apple", category_name: "Home gadgets", is_Available: 1 }, { product_id: 9, product_name: "Verifone", category_name: "Electronics", is_Available: 0 }],
result = data.reduce((r, o) => {
r[o.is_Available ? 'availableData' : 'notAvailableData'].push(o);
return r;
}, { availableData: [], notAvailableData: [] });

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

How to split an array of arrays based on certain condition?

Without converting your reactangles this is my solution:

var paths = [  [3,4,6,7],  [8,10],  [13]];
var rectangles = [{id:1,left:[],right:[2]},{id:2,left:[1],right:[11]},{id:3,left:[2],right:[4]},{id:4,left:[3],right:[5]},{id:5,left:[11],right:[6,12]},{id:6,left:[5],right:[7]},{id:7,left:[6],right:[]},{id:8,left:[],right:[9]},{id:9,left:[8],right:[10]},{id:10,left:[9],right:[2]},{id:11,left:[2],right:[5]},{id:12,left:[5],right:[]},{id:13,left:[],right:[9]}];
function getRectangle(index){ for (var i=0; i<rectangles.length; i++){ if (rectangles[i].id == index){ return rectangles[i]; } } return undefined;}
function isNeighbour(p1, p2) { var r1 = getRectangle(p1); var r2 = getRectangle(p2); if (r1 == undefined || r2 == undefined){ return false; } return r1.left.indexOf(p2) >= 0 || r1.right.indexOf(p2) >= 0 || r2.left.indexOf(p1) >= 0 || r2.right.indexOf(p1) >= 0;}
function groupPaths(paths) { var results = []; var neighb = []; for (var i=0; i<paths.length; i++){ if (paths[i].length == 1){ results.push(paths[i]); continue; } for (var j=0; j<paths[i].length; j++){ if (j+1 == paths[i].length){ neighb.push(paths[i][j]); results.push(neighb); neighb = []; continue; } while(isNeighbour(paths[i][j], paths[i][j+1])){ neighb.push(paths[i][j]); j = j+1; } neighb.push(paths[i][j]); results.push(neighb); neighb = []; } } return results;}
var res = groupPaths(paths);for (var i=0; i<res.length; i++){ for(var j=0; j<res[i].length; j++){ console.log(i + ': ' + res[i][j]); }}

Split an array of items into several arrays, given a condition

It is not shorter, but I would go for a more generic function which groups data into chunks based on a given property ("date" in your case) and some boundary values (you have 3), provided in ascending order. Then that function would return one more value, since 3 boundaries split an infinite range into 4 ranges, ...etc.

So this is what that function would look like:

function groupInRanges(data, prop, boundaries) {    // NB: boundaries must be sorted ascending.    return data.reduce((acc, item) => {        let index = boundaries.findIndex(boundary => item[prop] < boundary);        if (index < 0) index = boundaries.length;        acc[index].push(item);        return acc;    }, [[], ...boundaries.map(() => [])]);}
// Democonst now = Date.now();const day = 1000 * 3600 * 24;
const arr = [ { id: 1, date: now - day + 100 }, { id: 2, date: now - 2*day + 100 }, { id: 3, date: now - 5*day },];
// We are not interested in the first value (data older than 1 week):const [, week, yesterday, today] = groupInRanges(arr, "date", [now-day*7, now-day*2, now-day]);
console.log(today, yesterday, week);

Split the array and put it on IF statement each of array

There are few improvements that need to be done.

  • Comparing string with an array is wrong
  • When the idea is to append, then why to build an array, simply append within the loop

You can try following

$("table tr.odd a").each(function() {
var that = this;
var q = $(this).attr("href");
var e = $(this).parent().html();
$("table tr.even a").each(function() {
var w = $(this).attr("href");
if (q == w) {
$(this).clone().insertAfter($(that));
}
});
});

For reference - plunker

How to split an array according to a condition in numpy?

import numpy as np

def split(arr, cond):
return [arr[cond], arr[~cond]]

a = np.array([1,3,5,7,2,4,6,8])
print split(a, a<5)

a = np.array([[1,2,3],[4,5,6],[7,8,9],[2,4,7]])
print split(a, a[:,0]<3)

This produces the following output:

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

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

How to split an array into unequal parts according to a condition in python?

This is slightly different from @azro solution, but conceptually the same.
You make use of a tmp to accumulate the numbers until the if condition is valid, otherwise you append tmp to result and you initiate a new tmp with the current number in it.

a = [97, 122, 98, 111, 98, 111, 98, 101, 101, 103, 103, 104, 97, 107, 107, 108]

result = []
tmp = []
for i, n in enumerate(a):
if i == 0 or n >= a[i-1]:
tmp.append(n)
else:
result.append(tmp)
tmp = [n]
result.append(tmp)

print(result)
[[97, 122], [98, 111], [98, 111], [98, 101, 101, 103, 103, 104], [97, 107, 107, 108]]

Splitting a Associative Array Based off if Condition of Value

You can skip the array_combine part, and just read the values into the final arrays as you fetch them.

while($row = $sql1->fetch_assoc()) {
if ($row['Quantity'] > 0) {
$newqtysabovezero[$row['SKU']] = $row['Quantity'];
} else {
$newqtysbelowzero[$row['SKU']] = $row['Quantity'];
}
}


Related Topics



Leave a reply



Submit