JavaScript Array Programs

1. Create and Display an Array

This program creates an array named fruits containing three elements, then logs the entire array to the console.

const fruits = ["Apple", "Banana", "Cherry"];
            console.log(fruits);

2. Add an Element to the End of an Array

Here, we add a new element, "Orange", to the end of the fruits array, then display the updated array.

fruits.push("Orange");
            console.log(fruits);

3. Remove the Last Element from an Array

This code removes the last element from the fruits array and prints the modified array to the console.

fruits.pop();
            console.log(fruits);

4. Find the Index of an Element in an Array

We find the index position of "Banana" within the fruits array and log it to the console.

const index = fruits.indexOf("Banana");
            console.log(index);

5. Remove an Element by Index Position

Using the index found previously, this example removes "Banana" from the array by its index position.

fruits.splice(index, 1);
            console.log(fruits);

6. Copy an Array

This program makes a copy of the fruits array into a new array called fruitsCopy, then logs the copy.

const fruitsCopy = fruits.slice();
            console.log(fruitsCopy);

7. Merge Two Arrays

Here, we create a new array by merging fruits with another array vegetables, and then display the merged array.

const vegetables = ["Carrot", "Tomato"];
            const produce = fruits.concat(vegetables);
            console.log(produce);

8. Find the Length of an Array

This simple program logs the number of elements in the fruits array.

console.log(fruits.length);

9. Iterate Over an Array

We use the forEach method to iterate over each element in the fruits array, logging both the index and the element.

fruits.forEach(function(item, index) {
                console.log(index, item);
            });

10. Filter an Array

This program demonstrates filtering the fruits array to find elements that start with the letter 'B', and logs the result.

const result = fruits.filter(fruit => fruit.startsWith('B'));
        console.log(result);

11. Merging Two Arrays without Duplicates

This example demonstrates how to combine two arrays into one, ensuring there are no duplicate values in the merged result. The Set object is used for its property of storing unique values, and the spread operator ... is employed to expand both arrays within a new array, which is then converted into a Set to remove duplicates, and back into an array.

const array1 = [1, 2, 3];
const array2 = [2, 3, 4];
const mergedArray = [...new Set([...array1, ...array2])];
console.log(mergedArray);

12. Finding the Intersection of Two Arrays

This code finds the common elements between two arrays, effectively calculating their intersection. The filter() method is used to create a new array containing only the items that exist in both original arrays, determined by the includes() method.

const firstArray = [1, 2, 3, 4];
const secondArray = [2, 4, 6, 8];
const intersection = firstArray.filter(value => secondArray.includes(value));
console.log(intersection); // Output: [2, 4]

13.Removing Falsy Values from an Array

This example filters out all falsy values (e.g., false, null, 0, "", undefined, and NaN) from an array. By passing the Boolean constructor function to the filter() method, it automatically removes all values that are considered falsy in JavaScript, leaving only truthy values.

const mixedArray = [0, "text", false, 4, "", null, undefined, "0"];
const truthyArray = mixedArray.filter(Boolean);
console.log(truthyArray); // Output: ["text", 4, "0"]

14.Flattening an Array of Arrays

The flat() method is used to flatten nested arrays into a single array. By specifying the depth level (in this case, 2), it controls how many levels of nesting will be flattened, accommodating arrays with varying degrees of depth.

const nestedArray = [1, [2, 3], [4, [5, 6]]];
const flatArray = nestedArray.flat(2); // Level of depth is 2
console.log(flatArray); // Output: [1, 2, 3, 4, 5, 6]


15. Grouping Objects by a Property

This technique uses the reduce() method to organize an array of objects into a structure grouped by a specific property, in this case, name. The accumulator (acc) starts as an empty object, and objects are added into arrays under keys that match their name property, creating a map-like structure.

const people = [
{ name: "John", age: 25 },
{ name: "Anna", age: 30 },
{ name: "John", age: 28 },
];
const groupedByNames = people.reduce((acc, current) => {
  (acc[current.name] = acc[current.name] || []).push(current);
  return acc;
}, {});
console.log(groupedByNames);

16. Grouping Objects by a Property

To create a deep copy of an array that includes nested arrays or objects, JSON.stringify() is used to convert the array to a JSON string, and then JSON.parse() is used to parse that string back into a new array. This ensures that changes to the nested elements of the copied array do not affect the original array.

const original = [[1], [2], [3]];
const deepCopy = JSON.parse(JSON.stringify(original));
original[0].push(2);
console.log(original); // Output: [[1, 2], [2], [3]]
console.log(deepCopy); // Output: [[1], [2], [3]]

17.Sorting an Array of Objects by Property

This example sorts an array of objects based on a numeric property (price) using the sort() method. The callback function provided to sort() dictates the sorting logic, comparing the price property of each object to determine their order.

const items = [
{ name: "Banana", price: 1 },
{ name: "Apple", price: 2 },
{ name: "Orange", price: 1.5 },
];
items.sort((a, b) => a.price - b.price);
console.log(items);

18.Finding the Difference Between Two Arrays

This code snippet finds elements that are in the first array but not in the second, effectively calculating the difference between the two arrays. The filter() method is used with a condition that filters out any elements present in the second array.

const arr1 = [1, 2, 3, 4, 5];
const arr2 = [4, 5, 6, 7];
const difference = arr1.filter(x => !arr2.includes(x));
console.log(difference); // Output: [1, 2, 3]


19. Converting an Array of Objects into a Map

This demonstrates how to transform an array of objects into a Map, where each entry's key is an object's id and the value is the object itself. The Map object provides an efficient way to store key-value pairs and can be more performant for certain operations than an object.

const products = [
{ id: 1, name: "Pencil", price: 1.50 },
{ id: 2, name: "Notebook", price: 2.50 }
];
const productMap = new Map(products.map(product => [product.id, product]));
console.log(productMap);

20.Chunking an Array into Smaller Arrays of a Specific Length

This function splits a large array into smaller "chunks" or sub-arrays of a specified size. It's useful for processing or displaying large datasets in smaller, more manageable pieces. The loop iterates over the original array, slicing it into arrays of chunkSize and pushing these to the chunks array.

const createChunks = (array, chunkSize) => {
const chunks = [];
  for (let i = 0; i < array.length; i += chunkSize) {
    chunks.push(array.slice(i, i + chunkSize));
  }
  return chunks;
};
const data = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const chunkedData = createChunks(data, 3);
console.log(chunkedData); // Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]