Group objects by one of its params with javascript

Related searches

Basically I would want to transform this

[
  { key: 0, name: 'Some name' },
  { key: 0, name: 'Some name' },
  { key: 1, name: 'Some name' },
  { key: 1, name: 'Some name' },
]

To this where every object with the key of 0 would go into the first array and every object with the key of 1 would go into the second array.

[
  [
    { key: 0, name: 'Some name' },
    { key: 0, name: 'Some name' },
  ],
  [
    { key: 1, name: 'Some name' },
    { key: 1, name: 'Some name' },
  ],
];

Would really not mind using lodash for this but couldn't find the correct array method.


This is how I'd solve it with reduce:

const firstArray = [
  { key: 0, name: 'Some name' },
  { key: 0, name: 'Some name' },
  { key: 1, name: 'Some name' },
  { key: 1, name: 'Some name' },
]

const secondArray = firstArray.reduce((acc, elem) => {
  acc[elem.key] = [...(acc[elem.key] || []), elem];
  return acc
}, [])

console.log(secondArray)

How to group an array of objects through a key , Understand how to group an array of objects using one of its key. We will achieve this function using array reduce in javascript. The parameters, in a function call, are the function's arguments. JavaScript arguments are passed by value: The function only gets to know the values, not the argument's locations. If a function changes an argument's value, it does not change the parameter's original value. Changes to arguments are not visible (reflected) outside the function.


var array = [
  { key: 0, name: 'Some name' },
  { key: 0, name: 'Some name' },
  { key: 1, name: 'Some name' },
  { key: 1, name: 'Some name' },
];
array.sort(function(a,b){return a.key - b.key})
var temp = array[0].key;
var newArray = [];
var tempArray =[];
for(var i=0;i<array.length;i++){
    if(temp != array[i].key){
        newArray.push(tempArray);
        tempArray =[];
        temp = array[i].key;
    }
    tempArray.push(array[i]);
}
newArray.push(tempArray);

javascript group by property array of objects Code Example, “javascript group by property array of objects” Code Answer Your browser does not currently recognize any of the video formats available. add option to select jquery � add parameter submit form javascript � add parameter� by Kaashan Hussain We all deal with objects in one way or another while writing code in a programming language. In JavaScript, objects provide a way for us to store, manipulate, and send data over the network. There are many ways in which objects in JavaScript differ from objects in other mainstream programming languages, like Java. I will try to cover that in a another topic. Here, let us


You should be able to use Array.reduce for this purpose

lodash offers the groupBy function which suits this application nicely.

For example:

let a = [
  { key: 0, name: 'Some name' },
  { key: 0, name: 'Some name' },
  { key: 1, name: 'Some name' },
  { key: 1, name: 'Some name' },
];

let res = Object.values(a.reduce((acc, r) => { 
    acc[r.key] = (acc[r.key] || []).concat([r]);
    return acc;
}, {}));


console.log("Result:",res);


// You can also use lodash groupBy (which is more concise)
console.log("Using lodash:",Object.values(_.groupBy(a, "key")))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

consolelog.io => groupBy() in Javascript, Sometimes it'd be nice to group an array of objects by a common key value, Turns out there isn't a groupBy() method out of the box in Javascript, but it So we call reduce on our array and pass in two parameters, the first is� The task is to pass a string as a parameter on onClick function using javascript, we’re going to discuss few techniques. Example 1: This example simply put the argument which is string in the onClick attribute of the button which calls a function with a string as an argument using onClick() method .


You can achieve this by simply looping over your existing array and pushing the results to a newly created multidimensional array. This is, in my opinion, is the most readable way.

const mainArray = [
  { key: 0, name: 'Some name' },
  { key: 0, name: 'Some name' },
  { key: 1, name: 'Some name' },
  { key: 1, name: 'Some name' },
];

// create an empty array to store our results
const result = [];

mainArray.forEach(x => {
  const key = x.key;
  // Instantiate a new array if it does not exist 
  // for the given key.
  if (!result[key]) {
  	result[key] = [];
  }
  
  // push the object to the array
  result[key].push(x)
});

console.log(result);

JavaScript group an array of objects by key, The reduce() method executes a reducer function (that you provide) on each member of the array resulting in a single output value. let group =� Javascript always pass by value so changing the value of the variable never changes the underlying primitive (String or number). In Javascript objects and arrays follows pass by reference.


 function groupData(){
       var mainArray = [
        { key: 0, name: 'Some name' },
        { key: 0, name: 'Some name' },
        { key: 1, name: 'Some name' },
        { key: 1, name: 'Some name' },
      ];  
      
      var unique = [...new Set(mainArray.map(item => item.key))];
      	var tempArrays = new Array(parseInt(unique.length));   
      	for(var k = 0; k < unique.length; k++){
        if(! tempArrays[k] ){
        	tempArrays[k] = [];
        }
         
          for(var i = 0; i < mainArray.length; i++){
    		if (mainArray[i].key == unique[k]){        	 
              tempArrays[k].push(mainArray[i]);
             }
          }  
        }
        console.log(tempArrays);
    }
<input type="button" onClick="groupData();" value="Group Data">

A vanilla JS equivalent of lodash's groupBy() method, What groupBy() does The groupBy() method takes a collection of items as an array and groups them together in an object based on some criteria. The array to group items from * @param {String|Function} criteria The criteria� One interesting feature of the arguments object is that it aliases function parameters in non strict mode. What this means is that changing arguments[0] would change parameter1. Rest Parameters. Rest Parameter is an ES6 addition to JavaScript. To create a rest parameter prefix the last parameter in a function definition with ellipsis(…).