Looking to organize data based on duplicate values within an array using Javascript in the Vue framework

Can anyone provide assistance?

Data = [{"name":A,"val":20}, {"name":B,"val":7}, {"name":C,"val":20}, {"name":D,"val":8}, {"name":E,"val":5}]

SortedValues = [20, 20, 7, 8, 5]

I would like the output to be like this -->

Sorted_names = [A,C,D,B,E]   or   Sorted_names = [C,A,D,B,E]

Answer №1

Basic example of using forEach on a list of SortedValue, along with utilizing find to search for items in an array called Obj:

let Obj = [{"name":"A","val":20}, {"name":"B","val":7}, {"name":"C","val":20}, {"name":"D","val":8} , {"name":"E","val":5}]

let SortedValue = [20, 20, 7, 8, 5];
let result = [];

SortedValue.forEach(x => {
   let findObj = Obj.find(y => y.val === x);
   if (findObj) {
      result.push(findObj.name);
      Obj.splice(Obj.map(z => z.name).indexOf(findObj.name), 1); 
   }
});

console.log(result);

Answer №2

Utilizing both the sort and map functions would be my approach

data = [{"name":"A","val":20}, {"name":"B","val":7}, {"name":"C","val":20}, {"name":"D","val":8}, {"name":"E","val":5}]

const sorted_names = data.sort((a,b) => b.val - a.val).map(entry => entry.name)

console.log(sorted_names)

Answer №3

Here are a few techniques for sorting with the use of sort.

const collection = [{name:"Z", val: 10}, {name: "X", val: 15}, {name: "Y", val: 8}, {name:"W",val:13}, {name:"V",val:20}];

const nameSorted = collection.sort((x, y)=> { 
    if (x.name > y.name) return 1;
    if (x.name < y.name) return -1;
    return 0;
}).map(item => item.name);
console.log('sorted names: ', nameSorted);


const simplifiedNameSort = collection.sort((x, y)=> x.name < y.name ? -1 : x.name > y.name ? 1 : 0).map(item => item.name);
console.log('simplified name sorting: ', simplifiedNameSort);

const valueSorted = collection.sort((x, y)=> x.val - y.val).map(item => item.name);
console.log('sorted values: ', valueSorted);

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

After making 5 Ajax get requests, there is no response being received

Currently, I'm facing an issue when trying to retrieve information from the MongoDB server to the frontend using an AJAX GET request. Everything works smoothly until I attempt to call the JavaScript function multiple times. Strangely, if I call the fu ...

Middleware in Express not producing results

Here is the code I am currently using: var express = require('express'); var app = express(); app.use(express.bodyParser()); app.use(express.cookieParser()); var port = Number(process.env.PORT || 5000); app.get('/test/:id', function(r ...

Dynamic component in VueJS transitions is not functioning properly

Objective: To utilize dynamic components in creating personalized and reusable transition components for Vue V3. The vue2-transitions package found on npm uses a similar approach to the one mentioned below, but it is not compatible with v3. Therefore, I d ...

Unable to establish a local dependency link with npm

Attempting to connect my local project testabc123 to myproject using the usual method: cd testabc123 npm link cd ../myproject npm link testabc123 However, encountering an error message: npm ERR! code E404 npm ERR! 404 Not Found - GET http://registry.npmjs ...

Discovering the art of incorporating various color palettes within a single stylesheet using HTML

I'm curious about incorporating multiple color schemes into a single stylesheet that can be activated by clicking, similar to the functionality found in platforms like WordPress and Magento. These platforms offer themes with various color options avai ...

An error of undefined Angular Service/Factory has occurred

I created a factory service called siteCollection: spApp.factory('siteCollection', function(){ return { usersObject : [], getUsers : function (){ $().SPServices({ operation: "GetUserCollectionFromSite", completef ...

Having trouble with the Moment.js diff function in your React Native project?

Within my React Native application, I have implemented Moment.js and included the following code snippet: const expDate = moment(new Date(val)).format('MM-DD-YYYY'); const nowDate = moment().format('MM-DD-YYYY'); const diff = nowDate.d ...

Exploring the Power of Asynchronous Operations with Await and Async in

I have a basic understanding of how to use await/async in Angular 2 with the following example: async getValueWithAsync() { const value = <number>await this.resolveAfter2Seconds(20); console.log(`async result: ${value}`); } In my Angular ...

Leveraging Ajax for establishing session and displaying outputs

Trying my best to make this work with AJAX, but it's a new concept for me. So bear with me as I figure this out... I've posted a couple of questions about resolving the issue at hand and we've made progress. However, a new challenge has pre ...

Exploring the power of ES6 map function within React stateless components

I have a React application that fetches an array of objects from an API response. I want to display each object's details in an accordion format. Using the react-accessible accordion library, I created a React Stateless Component to achieve this. Each ...

Creating a Vue template using Javascript is a straightforward process

My app has a specific scenario where I need to define a template using JavaScript. For instance, after importing my template import MyTemplate from "./MyTemplate"; export default { components: {MyTemplate}, } Is it possible to declare the tem ...

Auto language-switch on page load

Wondering if using jQuery is the best approach to create a single French page on my predominantly English website. I want it to work across multiple browsers on pageload, currently using HTML replace. jQuery(function($) { $("body").children().each(funct ...

Set a variable equal to the output of an external function, but receive an undefined value in

I've been facing an issue where I'm trying to store the value of an external function in a JavaScript variable, but it keeps returning undefined. The external function in question is designed to search for a specific record within a database: f ...

Associate a unique identifier string with a randomly generated integer identifier by Agora

For my current web project, I am utilizing a String username as the UID to connect to the channel in an Agora video call. However, I now need to incorporate individual cloud recording by Agora into the project. The challenge lies in the fact that cloud r ...

Revamping the values attribute of a table embedded in a JSP page post an AJAX invocation

I am encountering an issue with displaying the content of a table. The table's data is retrieved via an AJAX request when clicking on a row in another table on the same page. Here is my code for the JSP page: <table id="previousList" class="table" ...

Retrieve pixel information upon touch in an Appcelerator Titanium application on Android or iPhone

Can pixel level data of an image view be accessed using Titanium Mobile on Android/iPhone? ...

Issues encountered when utilizing the successCallback function in ag-grid

I'm encountering an issue with a Vue component that has an ag-grid grid (infinite model). I need to access its params in order to use the successCallback method directly within another method in the component, subsequent to setting the datasource. In ...

Having trouble shutting down the window using Electron and Socket io

I embarked on a chat application project using NodeJS and Socket.io, everything was running smoothly. However, when I decided to integrate my app into the Electron framework, the chat window opened but I encountered an issue with the close button not func ...

A guide on transferring a Vue component to a custom local library

After successfully creating components using template syntax (*vue files), I decided to move common components to a library. The component from the library (common/src/component/VButton): <template> <button ... </button> </templat ...

Validating data on the server side using Vuelidate

I am currently exploring the integration of both frontend and backend validation techniques. For instance, in a registration form where a user inputs an email address, there is an email validator applied on the frontend and a unique validator enforced on ...