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

What is the process for transmitting data using an Ajax Query to a Controller and subsequently displaying a new JSP page returned by the Controller?

One issue I am facing involves sending data to a Spring Boot Controller through an AJAX Query and then loading a new JSP page. When I send data to the url in the AJAX Query, which matches the URL in my controller class, it executes the code within that met ...

Unknown CSS element discovered: bootstrap, gradient, carousel

I recently created a random quote app using javascript, jQuery, and bootstrap on Codepen. Everything worked perfectly there. However, when I organized the files, pushed them to git, and tried to view the app from Safari, I encountered some warnings and t ...

I need help figuring out the right way to define the scope for ng-model within a directive

I found a straightforward directive to automate sliders: app.directive('slider', function() { return { restrict: 'AE', link: function(scope, element, attrs) { element.slider({ value: scop ...

The problem of removing issue divs persists despite Jquery's efforts

Just yesterday, I successfully created a Commentbox using PHP, HTML, and ajax. The beauty of the ajax part is that it allows me to delete a comment without having to refresh the page. To achieve this, I assign a unique id to each comment (div) through the ...

Tips for serializing form inputs within a .change event using javascript, PHP, and CURL

I have a small project underway that involves using Ajax to retrieve data from a database and update a page. The user is able to build a dynamic query, creating a chain of query strings where each item in the chain affects the next one. This results in a l ...

Ensure accurate detection of invalid values for SVG Elements in React using jest testing framework

When testing my react app, I am attempting to capture any errors that are thrown or logged to the console. If a regular HTML element such as <p> contains invalid attributes like <p color={false}></p>, react will display an error via cons ...

Using Javascript to Manuever an Element via Arrow Inputs

Currently, I am in the process of developing a Tetris game with a rotating Tetris piece controlled by pressing the space bar. My next objective is to enable the movement of objects to the left and right using the arrow keys. After exploring various simila ...

Error: The "render" method is not available for the IncomingMessage object

While working on a basic application using node.js and express, everything seems to be in order except for this error that keeps popping up: res.render("aggregatedCostList",{ ^ TypeError: Object #<IncomingMessage> has no method 'render&ap ...

Efficient method invocation for objects within an array using functional programming techniques

Is there a way to execute a method that doesn't require arguments and doesn't return anything on each object within an array of objects that are all the same type? I've been trying to find a solution without resorting to using a traditional ...

Update the chosen option in a dropdown list with jQuery and javascript

I need to set the value of a column in a repeater so that once it's assigned, the column will display the current selection from the dropdown. I have the correct value to assign in $('#myname_' + rowIndex).text(), but when I try to assign t ...

Adding markers to a Leaflet map using coordinates retrieved from a Supabase database - a step-by-step guide

I am looking to incorporate markers on a map using coordinates stored in a Supabase database column. Below is my Vue code: <l-marker v-for="(marker, index) in markers" :key="index" ref="markersRef" :lat-lng="marker.po ...

Whenever a user tries to retrieve a page using ajax and then proceeds to submit the form associated with that page, they encounter

In my addQuestions.php file, I have four options available - single, multiple, matrix, and true false type questions with values 1-4 assigned to each respectively. To dynamically load the appropriate question type based on user selection, I am using AJAX w ...

Altering information with the use of history.pushState throughout time

I've created a template that I want to load using the jQuery .load() function. However, during testing, I discovered that it's not loading at all. Here is the code I'm trying to use for loading: function open() { history.p ...

Troubleshooting issue with TypeScript: Union types not functioning correctly when mapping object values

When it comes to mapping object values with all primitive types, the process is quite straightforward: type ObjectOf<T> = { [k: string]: T }; type MapObj<Obj extends ObjectOf<any>> = { [K in keyof Obj]: Obj[K] extends string ? Obj[K] : ...

Navigating the seamless integration of an API key with axios involves a systematic

Attempting to retrieve data from the specified api at using my provided api key. However, upon requesting the data, I received an error stating "Invalid key". Below is the code I am using: https://i.stack.imgur.com/jRwi5.png Here is the response I rece ...

The term 'string' is typically employed as a data type, yet in this instance it is being utilized as an actual value

Just started working with TypeScript and encountered an issue while trying to set the state. Encountered this error message: 'string' is a type and cannot be used as a value here. const state = reactive({ user: { uid: "", ...

Flipping the camera rotation matrix in three.js

I am struggling with a scenario involving objects and a camera being controlled by a trackball. Whenever I add a new object to the main object, I want it to maintain its original orientation regardless of how the camera has moved around. For instance, with ...

Expanding accordion functionality and implementing JavaScript events within a content template

Delving quickly into the code, below you will find the asp.net markup for an accordion that serves as a container for topic headlines as headers for each panel. The contents of these panels are comments to be moderated. <ajaxToolkit:Accordion runat="se ...

Unable to configure AngularJS inputs to have a blank default value

I am facing a peculiar issue where I am unable to initialize my input fields as blank/empty. Even after clearing the cache and performing a hard reload, Google Chrome seems to be auto-populating them with older cached values. Here is the current view: Th ...

Modifying button attribute through dropdown selection

In my project, I have a dropdown that gets its data from a database. Depending on the selection made in the dropdown, I would like to change the attribute of a button (data-uk-modal="{target:'#modal-'value of dropdown'}"). <select id "ci ...