Arrange the Proxy Array of Objects, the localeCompare function is not available

Encountering an error while attempting to implement ES6

arrayObj.sort(a,b) => a.property.localeCompare(b.property)
syntax:

Getting TypeError: a.property.localeCompare is not a function.

Suspecting that localeCompare might not be in scope, but unsure how to properly bind it within the sort method, especially since the data is stored in a proxy. Working with VueJS 3 environment, although relevance of this framework to the issue is unclear.

myData = 
Proxy {0: {…}, 1: {…}, 2: {…}, 3: {…}, 4: {…}}
[[Handler]]: Object
[[Target]]: Array(5)
0: {itemIndex: 1, itemFmt: 2, itemFmtName: 'Call To Order', guid: 'd66af412-00a0-4c49-b8b5-abaefb79fed0', maxCt: 1, …}
1: {itemIndex: 2, itemFmt: 6, itemFmtName: 'Title/Discussion/Motion', guid: '9f7b9d34-3fcb-42c7-866e-a56f71a8aa4f', maxCt: 0, …}
2: {itemIndex: 4, itemFmt: 6, itemFmtName: 'Title/Discussion/Motion', guid: '406bea5e-1cb0-4d90-96e9-9b80b64ff8ba', maxCt: 0, …}
3: {itemIndex: 5, itemFmt: 6, itemFmtName: 'Title/Discussion/Motion', guid: 'ad9aacda-5100-4eef-9ead-c61e1ec0c285', maxCt: 0, …}
4: {itemIndex: 7, itemFmt: 3, itemFmtName: 'Roll Call', guid: '1715f7a3-066d-4787-8233-a36df2a729a9', maxCt: 1, …}

myData.sort((a, b) => a.itemIndex.localeCompare(b.itemIndex))

Answer №1

localeCompare is a method specific to Strings, so trying to use it on a property that is a Number like a.itemIndex will not work.

If you need to sort by the numerical value of itemIndex, simply subtract one from the other:

const myData = [
  {itemIndex: 1, itemFmt: 2, itemFmtName: 'Call To Order', guid: 'd66af412-00a0-4c49-b8b5-abaefb79fed0', maxCt: 1 },
  {itemIndex: 2, itemFmt: 6, itemFmtName: 'Title/Discussion/Motion', guid: '9f7b9d34-3fcb-42c7-866e-a56f71a8aa4f', maxCt: 0},
  {itemIndex: 4, itemFmt: 6, itemFmtName: 'Title/Discussion/Motion', guid: '406bea5e-1cb0-4d90-96e9-9b80b64ff8ba', maxCt: 0},
  {itemIndex: 5, itemFmt: 6, itemFmtName: 'Title/Discussion/Motion', guid: 'ad9aacda-5100-4eef-9ead-c61e1ec0c285', maxCt: 0},
  {itemIndex: 7, itemFmt: 3, itemFmtName: 'Roll Call', guid: '1715f7a3-066d-4787-8233-a36df2a729a9', maxCt: 1},
]

// Sort the data by itemIndex in ascending order
myData.sort((a,b) => a.itemIndex - b.itemIndex)

console.log(myData)

If you want to sort based on the String values of itemFmtName, then using localeCompare would be appropriate:

const myData = [
  {itemIndex: 1, itemFmt: 2, itemFmtName: 'Call To Order', guid: 'd66af412-00a0-4c49-b8b5-abaefb79fed0', maxCt: 1 },
  {itemIndex: 2, itemFmt: 6, itemFmtName: 'Title/Discussion/Motion', guid: '9f7b9d34-3fcb-42c7-866e-a56f71a8aa4f', maxCt: 0},
  {itemIndex: 4, itemFmt: 6, itemFmtName: 'Title/Discussion/Motion', guid: '406bea5e-1cb0-4d90-96e9-9b80b64ff8ba', maxCt: 0},
  {itemIndex: 5, itemFmt: 6, itemFmtName: 'Title/Discussion/Motion', guid: 'ad9aacda-5100-4eef-9ead-c61e1ec0c285', maxCt: 0},
  {itemIndex: 7, itemFmt: 3, itemFmtName: 'Roll Call', guid: '1715f7a3-066d-4787-8233-a36df2a729a9', maxCt: 1},
]

// Sort the data by itemFmtName alphabetically
myData.sort((a,b) => a.itemFmtName.localeCompare(b.itemFmtName))

console.log(myData)

Answer №2

It has been previously stated that the localeCompare method is specifically designed for strings.

Presented below is a utility function that verifies if the sorting parameter is a string or a number.

const data = [
  { index: 4, value: 'c' },
  { index: 2, value: 'a' },
  { index: 3, value: 'b' },
  { index: 1, value: 'd' },
]

const sortHelper = (data, sortBy) => {
  if (data.find(x => typeof x[sortBy] !== 'number')) 
    // sort using localeCompare
    return data.sort((a,b) => a[sortBy].localeCompare(b[sortBy]))
  else
    // sort as numbers
    return data.sort((a,b) => a[sortBy] - b[sortBy])
}

console.log(sortHelper(data, 'index'));
console.log(sortHelper(data, 'value'));

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

Transmitting HTML5 application settings via URL

I am interested in creating an HTML5 app that utilizes the WebAudio API. This app will allow users to customize certain parameters. Users should be able to 'share' these settings by sending a share URL, which can be clicked by others to view the ...

javascript utilizing key inputs

Is there a way I can create a function that activates when the "A" key on my keyboard is pressed, sending a signal to nupp('/TS'), and stops sending the signal when the "A" key is released? <html> <head> <script src=\"htt ...

Utilize axios-cache-interceptor to enforce caching of responses from axios

Is it possible to configure axios to always return a cached response with the help of axios-cache-interceptor? import axios from 'axios' import { setupCache } from 'axios-cache-interceptor' const axiosInstance = axios.create({ timeou ...

invoke the modal function from a separate React file

I am currently studying react and nextjs. I am experimenting with calling a modal from another file but unfortunately it's not functioning as expected. Here is the code I used: Signin.js import { Modal } from "react-bootstrap"; import { u ...

Aggregate array based on specified criteria in ReactJS

Let's consider the following array data: array = [ { id: 1, count: 0.5 cost: 100 user: {id: 1, name: "John 1"}, type: {id: 1, name: "T1"}, period: {id: 1, name: "2021"} ...

Display the personalized list of user items on the MERN dashboard

I'm currently developing a React booking platform that interacts with my backend through a Rest API using axios and redux. My challenge now is to display personalized reservations and rooms for each user on the website. However, I'm facing an iss ...

The isolate scope variable is becoming undefined within the link function

When working with a directive that takes a data object and a function in its isolate scope, I encountered an issue. Inside the link function, I declared a method to be triggered on a button click event. The problem is that while the value passed to the me ...

Utilizing previously written HTML code snippets

While working on a page within a legacy application, I find myself repeatedly reusing a large HTML block of code. The entire HTML and JavaScript codebase is quite old. The specific HTML block in question spans over 200 lines of code. My current strategy in ...

Issue with primeng dropdown not displaying the selected label

When using the editable dropdown with filter feature from PrimeFaces, I've noticed that selecting an option displays the value instead of the label. Here is the code snippet: <div class="col-md-5 col-xs-12"> <p-dropdown [op ...

The script ceased functioning immediately following the inclusion of a case-insensitive search feature and interactive images

In the process of creating my inaugural project featuring a collection of images, I wanted to include a filter/search bar at the top. This bar would dynamically filter the displayed pictures based on user input. For example, typing "Aatrox" into the search ...

Deleting an item from a Vue.js list

I'm currently working on a project to develop a basic webpage that allows users to add or remove textboxes using vue.js. new Vue({ el: "#app", data() { return { list: [] }; }, methods: { deleteFromList(index) { this ...

Preserve the specific date and time in the designated timezone

Utilizing the react-datePicker library requires using new Date() as input. I need to save the user's selected date, time, and timezone in such a way that regardless of their location, they will see Feb 10 2024 02:00 BST in the Date Object. Currently, ...

Determining the value of an object property by referencing another property

Upon running the code below, I encounter the following error message: Uncaught TypeError: Cannot read property 'theTests' of undefined $(document).ready(function() { var Example = {}; Example = { settings: { theTests: $(&apo ...

Angular: Concealing a Component within a Controller

Being new to Angular, I am trying to figure out how to programmatically hide/show a component using the controller. I am having trouble understanding how to access my component and set ng-hide to false. Currently, my controller includes a service call. Af ...

Preserve the existing value and then check it against the updated value of a variable within JavaScript

I utilized an API that supplies me with information in JSON format, retrieved the price of a specific currency, and presented it on a screen using JavaScript. I encapsulated this process within a function that dynamically updates the information at set int ...

Custom React component - DataGrid

Just starting out in the world of React and attempting to create a custom component with parameters. I'm curious about the correct approach for achieving this. Here's my current code snippet - how do I properly pass Columns, ajax, and datasourc ...

Is there a way for a component to remove itself in Vue 2.0?

Can someone help me with this issue? The official documentation only mentions that $delete can use arguments 'object' and 'key' However, I am trying to delete a component by itself using the following code this.$delete(this) ...

Executing program through Socket.io alert

My NodeJS server sends notifications to clients when certain actions are performed, such as deleting a row from a grid. Socket.io broadcasts this information to all connected clients. In the example of deleting a row, one approach could be adding an `acti ...

I'm experiencing an issue where using .innerHTML works when viewing the file locally, but not when served from a web server. What could be causing this discrepancy?

Utilizing mootool's Request.JSON to fetch tweets from Twitter results in a strange issue for me. When I run the code locally as a file (file:// is in the URL), my formatted tweets appear on the webpage just fine. However, when I serve this from my loc ...

Issue encountered when attempting to batch delete documents within a subcollection: Error message displays "TypeError: n.indexOf is not a

When attempting to batch delete a document within a subcollection, I encounter some issues. There are scenarios where I may need to remove the same product document ID along with various history document IDs, or multiple product document IDs with differen ...