How to create a JavaScript function to reverse an array of objects?

peterking1697923543 peterking1697923543
Blog
How to create a JavaScript function to reverse an array of objects?


// Define a function that takes an array of objects as an argument
const reverseArray = (array) => {
  // Check if the argument is an array
  if (!Array.isArray(array)) {
    // If not, throw an error
    throw new Error('Argument must be an array');
  }
  // Create a new empty array to store the reversed elements
  const reversedArray = [];
  // Loop over the original array from the end to the beginning
  for (let i = array.length - 1; i >= 0; i--) {
    // Get the current element from the original array
    const element = array[i];
    // Check if the element is an object
    if (typeof element !== 'object' || element === null) {
      // If not, throw an error
      throw new Error('Array must contain only objects');
    }
    // Push the element to the reversed array
    reversedArray.push(element);
  }
  // Return the reversed array
  return reversedArray;
};

// Test the function with some examples
console.log(reverseArray([{a: 1}, {b: 2}, {c: 3}])); // [{c: 3}, {b: 2}, {a: 1}]
console.log(reverseArray([{name: 'Alice'}, {name: 'Bob'}, {name: 'Charlie'}])); // [{name: 'Charlie'}, {name: 'Bob'}, {name: 'Alice'}]
console.log(reverseArray([1, 2, 3])); // Error: Array must contain only objects
console.log(reverseArray('hello')); // Error: Argument must be an array

Comments (0)

U
Press Ctrl+Enter to post

No comments yet

Be the first to share your thoughts!