Group by, sort, merge in a Object that contains multi array

php sort multidimensional array by specific key value
php sort multi-dimensional array by multiple values
php sort multidimensional array by column
php sort multidimensional array by value
php sort multi-dimensional array by value ascending
php sort multidimensional associative array by value
php sort multidimensional array by value alphabetically
php sort multidimensional array by date

I have an object that contains 2 arrays that I want to handle by JavaScript

Or

{Array1: Array(11), Array2: Array(11)}

Array1:(11) ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'A', 'F', 'C', 'E']

Array2:(11) ['5', '7', '4', '3', '8', '1', '9', '1', '5', '4', '2']

My question is :

How can I group and sort that object to be like this

after group and sort

Then get top 3 rows by value with the rest that are merged in 1 row like:

I did the same with python combine with SQL but don't know how to do the same by using JavaScript only, here is what I did:

Add data to data frame which is already grouped and sorted in SQL

df1 = collection_condition(Grouped table)

Create new data frame - df2 -that contains top 3 from df1

df2 = df1.iloc[3:]

Create new data frame - df3 - that contains the rest from df1

df3 = df1.iloc[:3]

Then calculate total of value of df3

rest_total = df3["Array2"].sum()

Then add new line to df2

df2.loc[-1] = ["Others", rest_total]
df2.index = df2.index + 1 
df2 = df2.sort_index()

My plan here is:

  1. Try to group by that object (optional - you don't need to answer this one as I can manage to have a grouped object but any solution would be good as well)
  2. Have to sort that object so that I can cut it like I did with python or any suggest will be good as well.

Thanks


You could transpose the data, group it, sort it and get the top three values and the summed other values, transpose again and assign back to the object.

const
    transpose = (r, a) => a.map((v, i) => [...(r[i] || []), v]),
    group = (r, a) => {
        var temp = r.find(v => v[1] === +a[1]);
        if (!temp) {
            r.push([a[0], +a[1]]);
        } else {
            temp[1] += +a[1];
        }
        return r;
    }

var data = { Array1: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'A', 'F', 'C', 'E'], Array2: ['5', '7', '4', '3', '8', '1', '9', '1', '5', '4', '2'] },
    temp = Object
        .values(data)
        .reduce(transpose, [])
        .reduce(group, [])
        .sort(({ 1: a }, { 1: b }) => b - a)
        .reduce((r, a, i) => r.concat([i < 4 ? a : ['OTHERS', r.pop()[1] + a[1]]]), [])
        .reduce(transpose, []);

[data.Array1, data.Array2] = temp;

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

Grouping Data, Grouping data is an important capability to have when doing data analysis. Fundamentally, d3.nest is about taking a flat data structure and turning it into a nested one. And that has been converted to a nice array of objects via our data reading The order of the nest.key calls determines the order of the grouping. sort() method is a java.util.Arrays class method.. Syntax: public static void sort(int[] arr, int from_Index, int to_Index) arr - the array to be sorted from_Index - the index of the first element, inclusive, to be sorted to_Index - the index of the last element, exclusive, to be sorted This method doesn't return any value.


One possible option in Python, given the arrays:

ari1 = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'A', 'F', 'C', 'E']
ari2 = ['5', '7', '4', '3', '8', '1', '9', '1', '5', '4', '2']

Build a dict to calculate the sum for each letter:

from collections import defaultdict

tmp = defaultdict(int)
for a, b in zip(ari1, ari2):
 tmp[a] += int(b)

print(tmp)
#=> defaultdict(<class 'int'>, {'A': 6, 'B': 7, 'C': 8, 'D': 3, 'E': 10, 'F': 6, 'G': 9})

Then build a sorted list, since dictionaries doesn't hold order:

sorted_tmp = sorted([ [k, v] for k,v in tmp.items() ], key = lambda x: -x[1] )
print(sorted_tmp)
#=> [['E', 10], ['G', 9], ['C', 8], ['B', 7], ['A', 6], ['F', 6], ['D', 3]]

Then slice the list and build the final result:

res = sorted_tmp[0:3] + [[ 'others', sum([x[1] for x in sorted_tmp[3:]]) ]]
#=> [['E', 10], ['G', 9], ['C', 8], ['others', 22]]

3 solutions for sorting multidimensional arrays by child keys or , 3 solutions for sorting multidimensional arrays by child keys or values in PHP < ?php //Method1: sorting the array using the usort function and a "callback The bubble sort method has already failed whereas method 3 in which The task is to group the books by genre and then sort each sub-array by the� The sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.


To do it in JavaScript, you can use combine the 2 arrays into an array of 2 objects, and then sort the arrays using the .sort() method.

var a1 = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'A', 'F', 'C', 'E'];
var a2 = ['5', '7', '4', '3', '8', '1', '9', '1', '5', '4', '2'];

function sortTable(){
    //Combine the 2 arrays into an array of objects
    //This is assuming that both arrays are of the same length.
    var i, table = [];
    for(i=0;i<a1.length;i++){
        table.push({
            //I'm assuming you are sorting numbers, so I use parseInt()
            "sorting":parseInt(a2[i]), //if a1 is the array you need to sort by, replace a2 with a1.
            "name":a1[i]
        });
    }
    
    //This is where the "magic" (sorting) happens
    table.sort(function(a,b){
        return b.sorting-a.sorting; //descending order
        //return parseInt(a.sorting)-parseInt(b.sorting); //ascending order
    });
    
    //At this point, your table is sorted in descending order
    //table[0] is your highest value.
    
    //EDIT: OOPS forgot to add merging
    var sum = 0;
    var nToDisplay = 3; //change accordingly
    var mergedTable = []; //creating a new table so that you still will have your original table
    for(i=0;i<nToDisplay;i++){
        mergedTable.push(table[i]);
    }
    
    for(i=nToDisplay;i<table.length;i++){
        sum+=table[i].sorting;
    }
    mergedTable.push({
        "sorting":sum,
        "name":"OTHERS"
    });

    //FOR OUTPUT
    out='<div><b>MERGED TABLE</b><br>';
    for(i=0;i<mergedTable.length;i++){
        out += mergedTable[i].name+" | "+mergedTable[i].sorting+"<br>";
    }
    out+="</div><hr />";
    
    out+='<div><b>ORIGINAL TABLE</b><br>';
    for(i=0;i<table.length;i++){
        if(i<3) out+="<b>";
        out += table[i].name+" | "+table[i].sorting+"<br>";
        if(i<3) out+="</b>";
    }
    out+="</div>";
    
    document.getElementById("out").innerHTML = out;
}
<h3>Array values:</h3>
<div>
  ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'A', 'F', 'C', 'E']</div>
<div>
  ['5', '7', '4', '3', '8', '1', '9', '1', '5', '4', '2']</div>
<div>
  <input type="button" value="Sort my table!" onclick="sortTable()"/>
</div>

<div><hr /></div>

<div id="out"></div>

Merge arrays into a new object array in Java, The task is to merge the two arrays of the same type into an object array such that order in the newly merged array and the elements of the first array precedes the Object[], toArray(), Returns an array containing the elements of this stream. Java Collections: A Collection is a group of individual objects represented as a � Array.create creates an array of a specified size and sets all the elements to provided values. Array.init creates an array, given a dimension and a function to generate the elements. Array.zeroCreate creates an array in which all the elements are initialized to the zero value for the array's type. The following code demonstrates these functions.


You can follow following steps.

  1. use map() to get an array of objects which contains both number and letter.
  2. Sort the array of object on the basis of num using sort()
  3. Get the part of array below 3 using slice()
  4. Add the values of that part using reduce()
  5. At last join the reduced part(part after row 3) with first 3 elements using concat()
  6. And then change the array of objects to an object of two arrays using reduce()

let obj = {arr1:['A', 'B', 'C', 'D', 'E', 'F', 'G', 'A', 'F', 'C', 'E'],arr2:['5', '7', '4', '3', '8', '1', '9', '1', '5', '4', '2']};
let temp = obj.arr2.map((num,i) => ({num:num,letter:obj.arr1[i]})).sort((a,b) => b.num - a.num);
/**/
let rowNumber = 3;
let merged = temp.slice(0,3).concat(temp.slice(3).reduce((ac,item) => ({num:Number(item.num) + Number(ac.num), letter:ac.letter + item.letter})));
merged = merged.reduce((ac,a) => {
  ac.arr1.push(a.letter)
  ac.arr2.push(a.num)
  return ac;
},{arr1:[],arr2:[]})
console.log(merged);

PHP, Sorting Arrays in PHP 5 � PHP | Find Intersection of two arrays � PHP | Check if two arrays contain same elements � How to merge arrays and preserve the keys in� The Property parameter of the Sort-Object cmdlet accepts an array (more than one) of properties upon which to sort. This means that I can sort on the process name, and then sort on the working set of memory that is utilized by each process (for example).


    var a = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'A', 'F', 'C', 'E']
var b = ['5', '7', '4', '3', '8', '1', '9', '1', '5', '4', '2']

var hsh = creteHashFromArrays(a, b)
hsh = sortArrayDescending(hsh)
hsh = iterateHash(hsh)
console.log(hsh)

function creteHashFromArrays(a, b) {
    var h = {};
    for(ele in a) {
        if (a[ele] in h) {
            h[a[ele]] = h[a[ele]] + parseInt(b[ele])
        } else {
            h[a[ele]] = parseInt(b[ele])
        }
    }
    return h;
}

function sortArrayDescending(h) {
    var r = {}
    Object.keys(h).sort(function(a,b){return h[b] - h[a]}).map(k => r[k] = h[k])
    console.log(r)
    return r;
}

function iterateHash(r) {
    result = {}
    var x = Object.keys(r)
    for(i in x){

        if (i < 3) {
            result[x[i]] = r[x[i]]
        } else {
            if ("others" in result) {
                result["others"] = parseInt(result["others"]) + parseInt(r[x[i]])
            } else {
                result["others"] = parseInt(r[x[i]])
            }
        }
    }
    var obj = {
        "array_one": Object.keys(result),
        "array_two":  Object.values(result)
    }
    console.log(obj)
    return result;
}

Fiddle Example

array_multisort - Manual, array_multisort — Sort multiple or multi-dimensional arrays In this example, after sorting, the first array will contain 0, 10, 100, 100. of both worlds by merging content sorted either way according to the first caracter of the string: When sorting an array of (complex) objects, this function can give you a "Fatal error: Nesting� merge() The merge method merges the given array or collection with the original collection. If a string key in the given items matches a string key in the original collection, the given items's value will overwrite the value in the original collection:


PHP array_multisort() Function, Example. Merge two arrays and sort them as numbers, in descending order: <? php $a1=array� Second, sort the rivers array by the length of its element using the sort() method. We output the elements of the rivers array to the web console whenever the sort() method invokes the comparison function . As shown in the output above, each element has been evaluated multiple times e.g., Amazon 4 times, Congo 2 times, etc.


Sort merged array by array value in Twig?, This is only possible with a custom Twig Extension, since sorting a multidimensional array can't be done with Twig itself. I've written a plugin which extends� array_multisort() can be used to sort several arrays at once, or a multi-dimensional array by one or more dimensions. Associative keys will be maintained, but numeric keys will be re-indexed.


PHP Array: Associative, Multidimensional, A PHP array is a variable that stores more than one piece of related data in a the spaces containing chocolates represent the values stored in the arrays. The advantage of multidimensional arrays is that they allow us to group related data together. This function is used to sort the array using the key. Figure 4: This is how you reference an individual item within a multi-dimensional array. That's just a quick demonstration of how you can set up multi-dimensional arrays in PowerShell.