Use a try/catch block to handle errors in case the parameter does not exist

Sorting the data array is working fine for me, but now I want to pass values as parameters. However, if the user enters a 'parameter' that doesn't exist, I need to display an error message using TRY/CATCH. Can someone please help me understand why it's not working?

const data = [
    {
        "color": "Blue",
        "door": 3,
        "wheel": 3,
        "year": 2005,
        "brand": "GMC",
        "sold": false,
        "owner": "Chalmers Boobyer",
        "motor": 1.7,
        "assembled": "09/08/2022"
    },
    {
        "color": "Indigo",
        "door": 4,
        "wheel": 4,
        "year": 1996,
        "brand": "Lincoln",
        "sold": true,
        "owner": "Morten Coffin",
        "motor": 1.7,
        "assembled": "26/08/2021"
    }
];

function bubbleSort(arr, ord, prop){
    try{
    if(ord === 'asc'){
        for(let i = 0; i < arr.length; i++){
            for(let j = 0; j < arr.length - 1 - i; j++){
                if(arr[j][prop] > arr[j+1][prop]){
                    let temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                }
            }
        }
    } else if(ord === 'desc'){
        for(let i = 0; i < arr.length; i++){
            for(let j = 0; j < arr.length - 1 - i; j++){
                if(arr[j][prop] < arr[j+1][prop]){
                    let temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                }
            }
        }
    }
    return (arr);
}   catch(err){
    console.log(err);
}
}

console.log(bubbleSort(data, 'asc', 'wheel'));

Answer №1

let cars = [
  {
    "color": "Blue",
    "door": 3,
    "wheel": 3,
    "year": 2005,
    "brand": "GMC",
    "sold": false,
    "owner": "Chalmers Boobyer",
    "motor": 1.7,
    "assembled": "09/08/2022"
  },
  {
    "color": "Indigo",
    "door": 4,
    "wheel": 4,
    "year": 1996,
    "brand": "Lincoln",
    "sold": true,
    "owner": "Morten Coffin",
    "motor": 1.7,
    "assembled": "26/08/2021"
  }
];

/**
 * Swaps two objects within the array at specified indexes
 * @param {*} arr: The array containing the objects
 * @param {*} index1: Index of first object to swap
 * @param {*} index2: Index of second object to swap
 * @returns undefined
 */
function swap(arr, index1, index2) {
  let temp = arr[index1];
  arr[index1] = arr[index2];
  arr[index2] = temp;
}

/**
 * 
 * @param {*} arr: Array of objects
 * @param {*} index: Index of object to check property existence
 * @param {*} prop: Property name to check in the object
 * @returns Boolean | Throws Exception
 */
function propertyExists(arr, index, prop) {
  if (arr[index][prop] !== undefined) {
    return true;
  }
  throw new ReferenceError(`Property: ${prop} does not exist in arr[${index}]`);
}

/**
 * 
 * @param {*} ord: Sorting order 'asc' or 'desc'
 * @returns (arr, index1, index2, prop): Function to compare object properties at given indexes
 */
function getCompareFunction(ord) {
  if (ord === 'asc') {
    return (arr, index1, index2, prop) => { 
      return arr[index1][prop] > arr[index2][prop];
    }
  } else if (ord === 'desc') {
    return (arr, index1, index2, prop) => {
      return arr[index1][prop] < arr[index2][prop];
    }
  } else {
    throw `Invalid parameter for getComparator`;
  }
}


function bubbleSort(arr, ord, prop) {
  try {
    const compareArrayObjects = getCompareFunction(ord);
    for (let i = 0; i < arr.length; i++) {
      for (let j = 0; j < arr.length - 1 - i; j++) {
        propertyExists(arr, j, prop);
        propertyExists(arr, j + 1, prop);
        if (compareArrayObjects(arr, j, j + 1, prop)) {
          swap(arr, j, j + 1);
        }
      }
    }
    return data;
  } catch (err) {
    console.log(err);
  }
}


console.log(bubbleSort(cars, 'desc', 'wheel'));
console.log(bubbleSort(cars, 'desc', 'a'));

You can experiment with this approach

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create a custom function called `replaceValue` that searches for a specific value and replaces it with an

I'm curious about the possibility of creating a customized str_replace function to fill in placeholders. See the example below: $words = array('cat','mole'); $find='[blank]'; $string ="Lorem ipsum -[blank]- sit amet, con ...

What is the best way to iterate over an associative array and display the contents as a list?

After successfully setting up my initial array, I have been struggling to loop through each row and display the three columns/elements in a tag. Here is the var_dump of my array: array(27) { [3]=> array(3) { ["id"]=> string(3) "295" ["title"]=gt ...

Content placed in a div element via JavaScript will not wrap onto a new line

I recently created a div using JavaScript with the code mydiv.textContent="blahblahblahblahblahblah";. Although I have set the width of mydiv to 100px, the text string assigned to the div continues to run in one line without dropping down to the next lin ...

When processing a response from the backend (using express js), cookies are not being received in the browser while on localhost

I'm currently facing some difficulties with implementing authorization cookies within my application. Whenever I attempt to send a GET request to my API (which is hosted on port 8080) from my React frontend (running on port 3000), the cookies that I ...

Transfer JSON data between controllers without utilizing Services or Factory in AngularJS during routing

On my Dashboard page, I have an Object. When a user clicks on the Details Page from the Dashboard, it should redirect to the Details page. I am looking to pass the JSON Object from the Dashboard Controller to the Details Controller. Is there a way to do ...

Learn the process of utilizing JavaScript/Node.js to dynamically upload images onto a webpage directly from a database

Currently, I am developing a web application and building a user profile page where I aim to showcase user information along with a profile picture. Working with node/express/jade stack, I have a javascript file that manages loading the appropriate jade vi ...

This JavaScript function is designed to strip HTML elements from a given

"p" tags are disappearing after running the javascript, but they are needed for structuring purposes. Is there a way to retain the html tags in the hidden/secondary text block even after the javascript manipulation? function AddReadMore() { //This lim ...

Utilizing Chained Conditions in React JSX

Although the code below is functional and yields the desired outcomes, I can't help but question if there's a better way to do it. { Conditon1?<ChildComponent />:Condition2?<p>Hi</p>:<p>Bye</p> } I'm partic ...

How long does it take to delete and recreate a cloudfront distribution using AWS CDK?

I am currently undergoing the process of migrating from the AWS CDK CloudfrontWebDistribution construct to the Distribution Construct. According to the documentation, the CDK will delete and recreate the distribution. I am curious about the total duration ...

Utilizing React Typescript Discriminating Unions to choose between two different types based solely on props

In my project, I have a component that consists of different types: type Base = { color: string } type Button = { to: string } & Base type Link = { link: string linkNewTab: boolean } & Base type ComponentProps = Button | Link e ...

Ways to incorporate a php file based on the user's selection

I have numerous div elements, possibly a dozen or two, such as... <div class="mydivs" id="firstdiv"></div> <div class="mydivs" id="seconddiv"></div> <div class="mydivs" id="thirddiv"></div> <div class="mydivs" id="fo ...

JavaScript drop-down menu malfunctioning

I am currently in the process of learning web development languages, and I'm attempting to create a dropdown list using JavaScript (I previously tried in CSS without success). I would greatly appreciate it if you could review my code and let me know ...

Error encountered when attempting to retrieve JSON data in JavaScript due to being undefined

A snippet of code that reads and writes JSON data is presented below: var info; $(function () { $.getJSON("data.json", function (d) { info = d; }); $('.btn').click(function () { info['c-type'] = $('#c- ...

Using AngularJS to auto-fill input and textarea fields

In order to test local storage, I created a ToDo list using angularJS. Within my mainController, the following code snippet is present: $scope.saved = localStorage.getItem('todos'); $scope.todos = (localStorage.getItem('todos') !== n ...

Sending out a command does not equate to establishing Redux with an outcome

I've been grappling with this issue for the past 18 hours and I'm at a loss to figure out what's causing the problem. My redux setup is working smoothly as it dispatches actions and receives state correctly for other components. However, in ...

What causes adjacent elements in an int array to change when a number is appended in Golang?

I've been working on solving dynamic programming problems using Golang. One of the functions I wrote looks like this: func main() { fmt.Println(HowSum(5, []int{1, 2, 5})) } func HowSum(targetNum int, numbers []int) []int { retAry := make([][]in ...

How can I retrieve the number of links pointing to a specific property within a JavaScript object

I am faced with the following dataset: const main = 'test1'; const data = [ { from: 'test1', to: 'test2' }, { from: 'test2', to: 'test3' }, { from: 'test3', to: ...

Error encountered: Multer does not recognize the field when attempting to upload multiple files in a node.js environment

I would like to upload two files in one request using Node.js and I am utilizing multer for this task. Here is my request in Postman: https://i.sstatic.net/8ZEno.png Additionally, I am using multer in routing: router.post( "/Create", Uploa ...

Unable to locate the reference to 'Handlebars' in the code

I am currently attempting to implement handlebars in Typescript, but I encountered an error. /// <reference path="../../../jquery.d.ts" /> /// <reference path="../../../require.d.ts" /> My issue lies in referencing the handlebars definition f ...

What is the correct location to store the bower.json file?

I'm currently using bower 1.2.2 to handle my client-side libraries for the first time with a new node app. I'm unsure whether I should initialize bower in the main project root alongside gruntfile.js and package.json, or within the static directo ...