Split an array with custom function

split array javascript
split array into chunks javascript
javascript split array into equal parts
array slice
javascript split array into multiple arrays based on value
javascript split regex
split an array into multiple arrays javascript
lodash split array into chunks

i would like to split an array into multiple chunks but applying a function to it to decide how to create the chunks.

For example, if i have an array of letters, numbers or letters and numbers, apply a function to the array to split it into array of arrays of the previous categories.

let arr = ['a', 'b', '1', '2', 'a1', 'a2', 'c', '3', 'a3']
myChunkFunction(arr, myCustomSplitFunction)

// result
[['a','b','c'], ['1','2','3'], ['a1', 'a2','a3']]

Lodash has a chunk function but it splits into n chunks, also array has a slice function but you need to specify the begin and the end so how could i split with a custom function.

Try doing this

let arr = ['a', 'b', '1', '2', 'a1', 'a2', 'c', '3', 'a3']

const splitFn = (str) => Number.isInteger(+str) ? 0 : str.length == 1 ? 1 : 2
const myChunkFunction = (arr, fn) => arr.reduce((r,c) => {
   let t = fn(c)
   r[t] = [...r[t], c]
   return r
}, [[],[],[]])

console.log(myChunkFunction(arr, splitFn))

JavaScript String split() Method, from index 2 and first part {12, 10} add to the end . If expression is a zero-length string(""), Split returns an empty array, that is, an array with no elements and no data.

Hint

The key to the answer is to, somehow, reorganize the source array such that all the elements with the same key will be in the same place.

The easiest way I can think to solve it is by using hash-map. Each element in the hash-map will be a different array containing all the elements with the same key.

Try it for your self before you keep reading and see the full solution.


The implementation

As you can see, I solved it as functional as possible. To avoid mutations, I used reduce to iterate over the source array and put each element in the hashmap (by generating a key from the element).

I recreate the final hash-map over and over using shallow copy. Finally, I convert the hash-map to an array of array (because that was your demand) using Object.values

const splitArrayByKey = extractKey => array => {
    const arraysByKey_obj = array.reduce((hashMapOfArrays,element)=> {
        const key = extractKey(element);
        
        // if we already added an element with the same key, 
        // then we add the current element to there.
        // else, we create a new key and put the current element there.
        if(hashMapOfArrays.hasOwnProperty(key))
            return {
                ...hashMapOfArrays,
                [key]: [...hashMapOfArrays[key],element]
            };
        return {
            ...hashMapOfArrays,
            [key]: [element]
        };
    },{});

    // transform the arraysByKey_obj to an array of arrays:
    return Object.values(arraysByKey_obj);
};

// example 1:
const result1 = splitArrayByKey(element=>element)([1,2,3,1,2,3]);
console.log(result1);

console.log('------------------');

// example 2:
const result2 = splitArrayByKey(element=>element.id)([{id:1,x:1},{id:{},x:2},{id:"id",x:3},{id:1,x:4}]);
console.log(result2);

Using a for loop, slice and set function in the prototype of array. You can register custom functions in the prototype of a function, in this case you  2. Using a for loop, slice and set function in the prototype of array. You can register custom functions in the prototype of a function, in this case you can create a custom function with the name chunk that accomplishes our goal: /** * Define the chunk method in the prototype of an array * that returns an array with arrays of the given size.

Here is a way to do this via ES6:

let arr = ['a', 'b', '1', '2', 'a1', 'a2', 'c', '3', 'a3']

const splitFn = (str) => Number.isInteger(+str) ? 0 : str.length == 1 ? 1 : 2
const myChunkFunction = (arr, fn) => arr.reduce((r,c) => {
   let t = fn(c)
   r[t] = [...r[t], c]
   return r
}, [[],[],[]])

console.log(myChunkFunction(arr, splitFn))

The split() method divides a String into an ordered set of substrings, puts these substrings into an array, and returns the array. The division is  The task performed by the list comprehension function of getting the split chunks can also be done using chain function. This is more useful when we wish to handle larger lists as this method is more efficient.

const arr = ['a', 'b', '1', '2', 'a1', 'a2', 'c', '3', 'a3'];
const getClassification = function(x){
    const hasNumber = x.split('').some(x => parseFloat(x));
    const hasChar = x.split('').some(x => !parseFloat(x));

    if(!parseFloat(x) && (!hasNumber && hasChar)) return 0;
    else if(parseFloat(x)) return 1;
    else return 2;
}

const myChunkFunction = function(arr, classifier){
    let jaggedArray = [[], [], []];

    arr.forEach(x => {
        jaggedArray[classifier(x)].push(x);
    })

    return jaggedArray;
}

console.log(myChunkFunction(arr, getClassification));

I think this satisfies.

PHP 5, PHP 7). array_chunk — Split an array into chunks This function takes each few elements of an array and averages them together. It then places the  newStr = split (str) divides str at whitespace characters and returns the result as the output array newStr. The input array str can be a string array, a character vector, or a cell array of character vectors. If str is a string array, then so is newStr .

Implement our custom split function myCustomSplit which behaves the same way as outputArr - The array that will be returned as output. The split() method is used to split a string into an array of substrings, and returns the new array. Tip: If an empty string ("") is used as the separator, the string is split between each character. Note: The split() method does not change the original string.

In the same manner, we are to write a function that goes through the elements of the array received and split it into groups as specified by the size passed in. I'm using a SSRS report and I'm receiving the value on the above pattern ( it may contain any number of users), i tried to write a visual basic function in the report body ( Custom code) to split the above string and return the following value: X_User,Y_User. I tried to write this code inside the report body

Since the base of the array is 0, 1 is added to get the total word count. You can use a similar code to create a custom function in VBA that will take the text as input  Split and custom split options are not supported for sets, groups, parameters, and bins. Microsoft SQL Server only allows up to four split fields. To generate more than ten new fields, consider using a split or custom split on the field that was previously generated by a split or custom split.

Comments
  • What is the question? What you have there seems fine, you just need to define myCustomSplitFunction.
  • I don't have a chunk function that applies custom functions.
  • It would just be function myChunkFunction(array, splitFunction) { return splitFunction(array); }, and then you could call it exactly as you have in your code above.
  • If you need to do manipulations like this commonly, maybe consider using a library like lodash. In particular, you could do this easily via their _.groupBy and _.values functions.
  • The question is fine. Stop downvote just because you don't see: "my question is...." .
  • He wants to extract a key from each element by a given function and use that for re-grouping the elements. In your solution, you implicitly used the identity function to extract the key.
  • "I would like to split an array into multiple chunks but applying a function to it to decide how to create the chunks". And: myChunkFunction(arr, myCustomSplitFunction). The second param is the custom function.