How to use Array Methods with Object Arrays in best ways?

Array methods are built-in JavaScript functions we can apply on arrays and even array objects. Object arrays can store multiple values in a single array variable, and are often difficult to manipulate than simple arrays. However, we can apply array methods with object arrays as well. In our previous tutorials, we have learnt how to use array methods on simple arrays. Let’s have a look how we can use array methods on an array of objects.

Let’s consider the same array of objects for students we covered in our looping through object arrays tutorial.

 // Array of student objects
    var students_list= {
        {
            name: 'mary',
            age: 12,
            gender: 'female',
            grade: B

        },
        {
             name: 'alex',
             age: 14,
             gender: 'male',
             grade: B
        },
        {
             name: 'rita',
             age: 12,
             gender: 'female',
             grade: A
        },
        {
             name: 'harry',
             age: 13,
             gender: 'male',
             grade: C
        }
    };

Now, we go through some example array methods we can use on this object array.

Different Array Methods on Object Array

Inserting new object elements to an object array.

unshift() and push()

Suppose we need to add a new student to the students list, we can add it on both sides, the start and end with separate methods. unshift() adds a new student to the start of an array, whereas push() adds to the end. Let’s demonstrate this.

 var new_student = {
            name: 'sally',
            age: 13,
            gender: 'female',
            grade: A

        }
students_list.unshift(new_student ); // adds sally's details at start as index 0
students_list.push(new_student ); // adds sally's details at end as index 4

We can also add a new student in the middle of an array, by passing the index location where the new student should be inserted. Array splice method can be used for this in the following syntax.

Array.splice(
  {index of where to start},
  {number of items to remove},
  {items to add}
);

splice()

An array splice function adds new items at the defined point, and also removes the items present at that specific point. We can use it as follows.

 var new_student = {
            name: 'sally',
            age: 13,
            gender: 'female',
            grade: A

        }
students_list.splice(2, 0, new_student ); // adds sally's details at index 2 - case 1
students_list.splice(2, 1, new_student ); // adds sally's details at index 2 - case 2

You can use the splice method in many ways. The method has two purposes as stated above. However, passing a 0 as the second parameter, i.e. for number of items to remove, allows adding a new element, without removing previous.

In case 1, sally’s details come in place of rita, i.e. at index 2, and the rest of the array moves forward where rita goes at index 3, and harry at index 4.

In case 2, sally’s details come in place of rita, i.e. at index 2, here rita is removed from the list and replaced by sally. Keeping the rest of the elements at the same position.

To search of results from an array of objects, we can use the find and filter methods.

find()

We can use it the similar way as we did for simple arrays. However, here we need to refer to an object property to match the search criteria. The object property can be accessed via the dot or [] notation.

let student = students_list.find(student => student.gender === "female" && student.age === 12);

The above methods looks for female students of age 12, and returns search results based on the criteria mentioned. The first matching element is then returned, in this case, details of mary.

filter()

To return all matching records, we can use the filter method.

let student = students_list.filter(student => student.gender === "female" && student.age === 12);

The same details and search criteria, but with different array method used. filter method will return records for mary and rita, as they both pass the search criteria.

map()

We can use the map function to transform an array of objects into an array of different objects. If we want to classify our students into three groups based on their grades.

let percentile = students_list.map(student => {
  if (student.grade === 'A'){
    return "First Percentile";
  }
  if (student.grade === 'B'){
    return "Second Percentile";
  }
if (student.grade === 'c'){
    return "Third Percentile";
  }
});
console.log(percentile);
// output:
// ['Second Percentile','Second Percentile','First Percentile', Third Percentile]

sort()

Sorting is based on a value of a property every object has sort function can be used to sort an object arrays’ elements. However we need to provide a function to define the sorting mechanism.

For example, we want to sort students with increasing age, starting from the youngest.

let sortedStds = students_list.sort((s1, s2) => (s1.age > s2.age) ? 1 : (s1.age < s2.age) ? -1 : 0);
console.log(sortedStds);
// outputs details in the following order...
// mary, rita, harry, alex

The sort method will compare two objects and then put the first in the second place if the result of the sorting function is positive. 

some()

The include function is similar to array some or every function. Here we can check if all elements in an array passes a condition. For example.

students_list.some(student => student.gender === "female" && student.age === 12);
// true for 2 items in list
students_list.every(student => student.age >= 15);
// false for all