Using an array element to pass a parameter

Looking to pass an array element as a parameter in my function.

I have an array with elements Column1 and Column2. The code currently sorts the array based on either column1 or column2. Currently, I am passing 1 and 2 values as parameters with an if condition in the sorting code.

I aim to update the code to:

function sortGrid(ColumnName)

and

var val1 = a.ColumnName.toLowerCase()

Any thoughts or suggestions?

Code:

<html lang="">
<body>

<script>
var arr = [{"Column1":"A","Column2":"F"},{"Column1":"Z","Column2":"B"}];

    function sortGrid(col) {
        arr.sort(function (a, b) {
            if (col == 1)
            {
                var val1 = a.Column1.toLowerCase();
                var val2 = b.Column1.toLowerCase();
            };
            if (col == 2)
            {
                var val1 = a.Column2.toLowerCase();
                var val2 = b.Column2.toLowerCase();
            };

            if (val1 < val2)
                return -1
            if (val1 > val2)
                return 1
        });
    }

    sortGrid(1)
    console.log(arr[0].Column1)
    console.log(arr[1].Column1)

    console.log('-------------------')

    sortGrid(2)
    console.log(arr[0].Column1)
    console.log(arr[1].Column1)


</script>
</body>
</html>

Answer №1

To achieve this, simply use a[ColumnName]:

var arr = [{"Column1":"A","Column2":"F"},{"Column1":"Z","Column2":"B"}];

function sortGrid(colName) {
  arr.sort(function (a, b) {
    var val1 = a[colName].toLowerCase();
    var val2 = b[colName].toLowerCase();
    return   val1 < val2 ? -1
           : val1 > val2 ? 1
           : 0;
  });
}

sortGrid('Column1')
console.log(arr[0].Column1)
console.log(arr[1].Column1)

console.log('-------------------')

sortGrid('Column2')
console.log(arr[0].Column1)
console.log(arr[1].Column1)

Remember to ensure that you return 0 in case the values are equal, which is why I've utilized the ternary operator with a 0 included twice.

Answer №2

Here is an example of how you could structure your code:

var data = [{"Category":"Fruit","Quantity":10},{"Category":"Vegetable","Quantity":5}];

function sortData(category) {
    data.sort(function (a, b) {
       var value1 = a[category].toLowerCase();
       var value2 = b[category].toLowerCase();
       if (value1 < value2)
            return -1
        if (value1 > value2)
            return 1
    });
}

sortData('Category')
console.log(data[0].Category)
console.log(data[1].Category)

console.log('-------------------')

sortData('Quantity')
console.log(data[0].Category)
console.log(data[1].Category)

One more thing to note: when using var to declare variables within a function, they have function scope and declaring them multiple times within the same function is unnecessary but will not cause any issues.

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

Using raycasting in Three.js to select objects and adding animation

In my current project, I have found that raycasting selection works perfectly fine for static meshes. However, when it comes to animated meshes, I have encountered an issue where the ray selection does not take into account the movement of the mesh. Instea ...

Issue with angular directive scope not binding correctly

Good day I'm relatively new to Angular and directives, but I'm facing an issue with the scope (in my specific case). I have defined the directive as follows: angular.module('ToolBarMod', ['ngAria']) .controller('ToolBar ...

Is the indigo-pink color scheme fully implemented after installing @angular/material and scss using ng add command?

After running ng add @angular/material, we are prompted to choose a CSS framework and theme. I opted for indigo-pink and scss. Will the material components automatically inherit this theme, or do we need to take additional steps? When using normal CSS (wi ...

Addressing Performance Challenges in Urban Rendering with ThreeJS

Issue: I am facing significant performance problems while rendering a scene using Three JS. The main issue arises from rendering a large number of simple geometries (11,107). (edit) Each building has a unique height based on elevation data, a distin ...

Animation issue in Material UI autocomplete label feature

Hello, I am currently delving into the world of React and Material UI. I have been working on implementing the Material UI auto complete feature with chip functionality. You can see my progress here: https://codesandbox.io/s/runh6. Everything seems to be w ...

Extracting information from the identifier of an option within a dropdown menu <select>

I'm currently working on fetching data from a based on the choice made by the user. The data is coming from the OpenDota API. Upon inspecting the element, I can see that the option tag is being populated correctly. However, I believe I might be handl ...

Disabling related videos in React Native: A guide to preventing suggested content from appearing at the end of YouTube videos

Is there a way to turn off the display of related videos after a YouTube video ends in react native? I've tried the following code, but it doesn't seem to be working: state = { isPlaying: true, related :false, }; <YouTube apiKe ...

Generating unique names based on input from users

We are working with an array containing names and an input field where users can enter a string to receive name suggestions. The array includes names like Alex and Anna, and when the user types "a," we want to suggest these names. Below is the code snippet ...

How can I use the *ngFor directive in Angular 2 or Ionic applications?

I am currently working on an Ionic Project. Upon button click, a request is processed and data is received as shown below: public login() { //this.showLoading() var test33; this.auth.login(this.registerCredentials).subscribe(data => { ...

Showing an individual image when a particular list item is clicked using jquery

I have created an image slider that automatically transitions between images. However, I would like to have a specific image displayed when a particular list item is clicked in the round buttons below. For example, if the slider is showing the 5th image a ...

The Next.js React app is constantly loading without any interruptions

Just diving into Next.js and attempting to transform a single HTML page into a Next.js website in order to integrate sanity. Managed to import all necessary assets, but stuck with the persistent preloader issue. After inspecting elements, noticed that a fi ...

Unable to open Google Maps link within React application

I've set up a conditional link based on location, using the following code: <a href={`https://maps.google.com/maps?q=${delivery_branch.latitude},${delivery_branch.longitude}`} target={"_blank"} >{`${delivery_branch.street}, ${d ...

Error: The array contains an undefined image object

Currently, I am implementing a simple image preloading technique using promises. This function is integrated into a larger Angular (1.3.15) custom directive. Here is the JavaScript code snippet: function preLoad() { var deferred = $q.defer(); ...

Sorting a parent array in AngularJS using a child array's Date field as the basis

I have an array of arrays of objects with the following structure: parentArray = [ [{id:1, date:1505020200000}, {id:4, date:1505020200000 }], [{id:2, date:1504681500000}], [{id:3, date:1504671000000}, {id:20, date:1504671000000}] ] Each nested array cont ...

What Causes the Misalignment Between My Image and Text?

I am trying to randomly select a slide from the list of slides when the page loads, and then display it in the hero section of a website. However, I am facing an issue where the Image seems to be out of sync with the Text & Button (for example, displaying ...

Tips for building and implementing Angular URL Parameters for URLs in the form: "component/#/?id=..."

I am currently facing a situation where I have an application with an existing user base. I am looking to avoid disrupting their current links for a smoother transition. However, the previous links are in this format: (server)/viewer/#/?id=12. Please see t ...

Tips for integrating React into a jQuery-centric web application?

After diving into React, I'm eager to showcase my skills by implementing it on select pages as a proof-of-concept for my supervisor at work. Can anyone guide me on how to achieve this using traditional script tags instead of imports? So far, I'v ...

Is it better to append content in JQuery rather than replacing it with .innerHTML?

Here is a function designed to retrieve older wallposts from a user, 16 at a time, and add each chunk of 16 to the end of the current list in the div called "sw1". The function works well, except when there is a wallpost containing a video or embedded obj ...

An error occurred while trying to convert a circular data structure to JSON during an API request within another

Attempting to make an API call within another API call in this code, however encountering the following error: Error: Converting circular structure to JSON const express = require('express'); const router = express.Router(); const config = requi ...

Dialogue Inventory System

I am in the process of developing a conversation system that includes a page where users can view all of their conversations and select which one they want to reply to. The layout is structured as follows: You can view an image of the layout here. The co ...