Data manipulation in JavaScript

Mukesh Prajapati
10 min readJan 26, 2023

--

JavaScript is a powerful programming language that is widely used for both front-end and back-end development. One of the key features of JavaScript is its ability to manipulate data in a variety of ways. In this blog post, we will explore some of the most common techniques for manipulating data in JavaScript, with examples to help illustrate how each method works.

1. Array Manipulation

JavaScript arrays are a powerful tool for storing and manipulating data. Some of the most common array manipulation methods include:

push(): adds an element to the end of an array
Example:

let fruits = ['apple', 'banana', 'orange'];

// add 'mango' to the end of the array
fruits.push('mango');
console.log(fruits); // ["apple", "banana", "orange", "mango"]

// add 'kiwi' and 'pineapple' to the end of the array
fruits.push('kiwi', 'pineapple');
console.log(fruits); // ["apple", "banana", "orange", "mango", "kiwi", "pineapple"]

The push() method is used to add one or more elements to the end of an array. It takes one or more arguments, which are the elements to be added to the array.

It’s worth noting that push() modifies the original array and also returns the new length of the array after adding the new elements.

pop() : removes the last element of an array
Example:

let fruits = ['apple', 'banana', 'orange'];
let lastFruit = fruits.pop();
console.log(fruits); // ["apple", "banana"]
console.log(lastFruit); // "orange"

In this example, the pop() method is called on the fruits array, removing the last element “orange” from the array and returning it. The fruits array is then modified and now contains only the elements “apple” and “banana”.

You can also use pop() method to remove the specific element by using the index of that element, for example

let numbers = [1, 2, 3, 4, 5];
numbers.pop(2);
console.log(numbers); // [1, 2, 4, 5]

In the above example, the element at index 2 (which is 3) is removed from the numbers array using the pop() method.

It’s worth noting that pop() method changes the original array.

shift() : removes the first element of an array
Example:

let fruits = ['apple', 'banana', 'orange'];

// remove the first element of the array
let firstFruit = fruits.shift();
console.log(firstFruit); // "apple"
console.log(fruits); // ["banana", "orange"]

The shift() method removes the first element of an array and returns that element. It also reduces the length of the array.

It’s worth noting that shift() changes the original array, it removes the first element of the array. If you want to keep the original array intact and create a new one with the shifted elements, you can use the slice() method instead.

It is important to note that shift() method changes the original array, so if you want to keep the original array intact and create a new one with the shifted elements, you can use the slice() method instead.

unshift() : adds an element to the beginning of an array
Example:

let fruits = ['apple', 'banana', 'orange'];

// add a new element to the beginning of the array
fruits.unshift('lemon');
console.log(fruits); // ["lemon", "apple", "banana", "orange"]

// add multiple elements to the beginning of the array
fruits.unshift('kiwi', 'mango');
console.log(fruits); // ["kiwi", "mango", "lemon", "apple", "banana", "orange"]

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array. The elements are added in the order in which they appear in the arguments list, so the first argument will become the first element of the array, the second argument will become the second element, and so on.

It’s worth noting that the unshift() method modifies the original array, it does not create a new one

splice() : removes or adds elements to an array at a specific index Example:

let fruits = ['apple', 'banana', 'orange', 'mango', 'kiwi'];

// remove an element from index 2
fruits.splice(2, 1);
console.log(fruits); // ["apple", "banana", "mango", "kiwi"]

// remove multiple elements from index 1
fruits.splice(1, 2);
console.log(fruits); // ["apple", "kiwi"]

// add an element at index 1
fruits.splice(1, 0, 'lemon');
console.log(fruits); // ["apple", "lemon", "kiwi"]

// replace an element at index 2
fruits.splice(2, 1, 'pear');
console.log(fruits); // ["apple", "lemon", "pear"]

The splice() method is used to add, remove or replace elements in an array at a specified index. The method takes three parameters:

  • the first parameter is the index at which to start changing the array.
  • the second parameter is the number of elements to remove.
  • the third parameter (optional) is the elements to be added to the array.

It’s worth noting that splice() method changes the original array, it doesn’t create a new one.

It’s a very powerful method to manipulate arrays and It’s widely used when working with dynamic data.

slice() : returns a new array with selected elements from the original array
Example:

let fruits = ['apple', 'banana', 'orange', 'mango', 'pear'];

// slice the first three elements
let firstThree = fruits.slice(0, 3);
console.log(firstThree); // ["apple", "banana", "orange"]

// slice the last two elements
let lastTwo = fruits.slice(-2);
console.log(lastTwo); // ["mango", "pear"]

// slice elements from index 1 to 3
let middleElements = fruits.slice(1, 4);
console.log(middleElements); // ["banana", "orange", "mango"]

The slice() method takes two arguments, the first is the starting index and the second is the ending index(not included) of the elements to be included in the new array. If the starting index is negative, it starts counting from the end of the array. If the ending index is not provided, all elements from the start index to the end of the array will be included. The slice() method returns a new array containing the selected elements from the original array.

It’s worth noting that slice() doesn’t change the original array, it creates a new one with the selected elements.

forEach() : allows you to iterate over each element of an array and perform an action
Example:

let numbers = [1, 2, 3, 4, 5];

// print each number
numbers.forEach(function(number) {
console.log(number);
});

// Output:
// 1
// 2
// 3
// 4
// 5

The forEach() method takes a callback function as an argument, and this function is executed once for each element in the array. The callback function is passed three arguments: the current element, the current index, and the array the method is being called on.

let fruits = ['apple', 'banana', 'orange'];

fruits.forEach(function(fruit, index) {
console.log(index + ': ' + fruit);
});

// Output:
// 0: apple
// 1: banana
// 2: orange

As you can see, the forEach method is a simple way to iterate over an array, it’s a great method when you want to perform an action for each element in an array without changing the original array.

map(): creates a new array with the results of calling a provided function on every element in the calling array.
Example:

let numbers = [1, 2, 3, 4, 5];

// square each number
let squares = numbers.map(function(number) {
return number * number;
});
console.log(squares); // [1, 4, 9, 16, 25]

// convert array of numbers to array of strings
let strings = numbers.map(function(number) {
return number.toString();
});
console.log(strings); // ["1", "2", "3", "4", "5"]

The map() method takes a callback function as an argument, and this function should return the new value for the element. The map() method then returns a new array containing the result of applying the callback function to each element of the original array.

The callback function passed to map() method is called for each element of the array, and it takes three arguments: currentValue, index, and the array itself. This method is useful to iterate through an array, transform all elements and return a new array, it doesn’t change the original array.

filter(): creates a new array with all elements that pass the test implemented by the provided function.
Example:

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// filter even numbers
let evens = numbers.filter(function(number) {
return number % 2 === 0;
});
console.log(evens); // [2, 4, 6, 8, 10]

// filter numbers greater than 5
let greaterThanFive = numbers.filter(function(number) {
return number > 5;
});
console.log(greaterThanFive); // [6, 7, 8, 9, 10]

The filter() method takes a callback function as an argument, and this function should return a Boolean value indicating whether the element should be included in the new filtered array. The filter() method then returns a new array containing only the elements that pass the test implemented by the callback function.

It’s worth noting that filter() doesn’t change the original array, it creates a new one with the filtered elements.

2. Object Manipulation

JavaScript objects are another important data structure for storing and manipulating data. Some of the most common object manipulation methods include:

Object.keys() : returns an array of the keys of an object
Example:

let person = { name: 'John', age: 30, job: 'developer' };
let keys = Object.keys(person);
console.log(keys); // ["name", "age", "job"]

Object.keys() method returns an array of the keys of an object. In this example, we have an object “person” with three properties (name, age, and job) and we are using Object.keys() method to get an array of keys of this object which is [“name”, “age”, “job”].

In this way, you can extract the keys of an object and use them to access the values or perform any operation on them. This is useful when you want to iterate over an object and access its properties, or when you want to extract the keys of an object to use them in another context.

Object.values() : returns an array of the values of an object
Example:

let person = { name: 'John', age: 30, job: 'developer' };
let values = Object.values(person);
console.log(values); // ["John", 30, "developer"]

In this example, we have an object person with three properties: name, age, and job. We use the Object.values() method to extract an array of the values of the object, which are "John", 30, and "developer".

It’s worth noting that the order of the values in the returned array is the same as the order of the properties in the original object, and it can be used with any object, it doesn’t matter if it’s defined using literal notation or constructor notation.

It’s also worth noting that this method is not supported in all browsers, you may need to include a polyfill for older browsers.

Object.entries() : returns an array of the key-value pairs of an object
Example:

let person = { name: 'John', age: 30, job: 'developer' };
let entries = Object.entries(person);
console.log(entries); // [["name", "John"], ["age", 30], ["job", "developer"]]

As you can see, the Object.entries() method takes an object as an argument and returns an array of its key-value pairs. Each element of the returned array is itself an array with two elements: the first element is the key and the second element is the value.

You can also use the Object.entries() method in conjunction with the forEach() method to iterate over the key-value pairs of an object:

let person = { name: 'John', age: 30, job: 'developer' };
Object.entries(person).forEach(function([key, value]) {
console.log(key + ': ' + value);
});

// This will output:

name: John
age: 30
job: developer

Alternatively, you can use the for...of loop to iterate over the array returned by Object.entries() and have access to the key and value of the object.

let person = { name: 'John', age: 30, job: 'developer' };
for (let [key, value] of Object.entries(person)) {
console.log(key + ': ' + value);
}

As you can see, using Object.entries() method can be useful when you need to work with the key-value pairs of an object in JavaScript.

Object.assign() : merges two or more objects together
Example:

let obj1 = { name: 'John', age: 30 };
let obj2 = { job: 'developer', city: 'New York' };
let obj3 = Object.assign(obj1, obj2);
console.log(obj3); // { name: 'John', age: 30, job: 'developer', city: 'New York' }

In this example, the Object.assign() method is used to merge obj1 and obj2 into a new object called obj3. The properties of obj2 are added to obj1, and any duplicate properties are overwritten by the values of obj2. The original obj1 and obj2 objects are not modified.

You can also use Object.assign() to create a new object and merge other objects into it:

let obj1 = { name: 'John', age: 30 };
let obj2 = { job: 'developer', city: 'New York' };
let obj3 = Object.assign({}, obj1, obj2);
console.log(obj3); // { name: 'John', age: 30, job: 'developer', city: 'New York' }

It’s also possible to merge multiple object together using the object spread operator (…)

let obj1 = { name: 'John', age: 30 };
let obj2 = { job: 'developer', city: 'New York' };
let obj3 = { ...obj1, ...obj2};
console.log(obj3); // { name: 'John', age: 30, job: 'developer', city: 'New York' }

Object.assign() is a great method for merging objects together, it’s commonly used in libraries and frameworks to extend objects or configure settings.

It’s worth noting that if the properties of the object are object themselves, the properties are not merged, but the reference is copied, so if the object inside the property is modified, it will also be modified in the final object.

for…in : allows you to iterate over the properties of an object
Example:

let person = { name: 'John', age: 30, job: 'developer' };

for (let key in person) {
console.log(key + ': ' + person[key]);
}

The for…in loop allows you to iterate over the properties of an object. In the example above, the variable “key” is set to the name of each property in the “person” object, and the value of each property is accessed using the object notation person[key].

The output will be:

name: John
age: 30
job: developer

It’s worth noting that for…in will also iterate over any properties from the prototype chain, so it may include properties that you don’t expect. To avoid this, you can use Object.hasOwnProperty(key) to check if the property is an own property of the object before accessing it.

for (let key in person) {
if(person.hasOwnProperty(key)){
console.log(key + ': ' + person[key]);
}
}

Also, for…in is not guaranteed to iterate over the properties in a specific order, so it’s not suitable for use cases that rely on order. In that case, you could use other options like forEach() or for...of loop.

delete : removes a property from an object
Example:

let person = { name: 'John', age: 30, job: 'developer' };
console.log(person); // { name: 'John', age: 30, job: 'developer' }

delete person.age;
console.log(person); // { name: 'John', job: 'developer' }

In this example, we first define an object person with three properties: name, age, and job. We then use the delete operator to remove the age property from the object. After the deletion, the person object no longer has the age property and the output of the second console.log statement shows this.

It’s worth noting that the delete operator only affects object properties and not variables or array elements. If you want to delete an element from an array, you can use the splice() method to remove the element from the array.

Also, delete operator only deletes own properties of an object, it cannot delete inherited properties.

Thank you for reading 🙏

--

--