Tips for enhancing performance in my code by extracting a distinctive element from an array - using Javascript

When working with an array containing data from 5000 users, my code's performance slows down significantly, especially when trying to extract unique values while also prioritizing phone numbers over null values.

The code snippet provided below implements two conditions:

Firstly, extracting unique values

Secondly, checking whether the phone number is null or not, giving preference to records with existing phone numbers.

var arr = [
  ["Wong", ""],
  ["Wong", "0143213123"],
  ["Ali", "0177213123"],
  ["Ali", "0177213123, 0124545345"],
  ["Ali", ""],
  ["Imran", "0133454335"]
];

function uniq(arr) {
  var seen = [];
  for (i = 0; i < arr.length; i++) {
    var a = arr[i][0];
    var a2 = arr[i][1];
    var c = true;
    for (x = 0; x < seen.length; x++) {
      var b = seen[x][0];
      var b2 = seen[x][1];
      if (b == a) {
        c = false;
        if ((b2.trim() == '' || b2.indexOf(',') == -1) && (a2.trim() != '')) {
          seen[x][1] = a2.trim();
          break;
        }
        break;
      }
    }
    if (c == true) {
      seen.push(arr[i]);
    }

  }
  return seen;
}

Upon executing the code, the result is as follows:

var arr = uniq(arr);
console.log(arr);

[
  ["Wong", "0143213123"],
  ["Ali", "0177213123, 0124545345"],
  ["Imran", "0133454335"]
];

Find this on jsfiddle here

Answer №1

If you want to consolidate data for each name using the reduce method, you can try the following approach:

var arr = [["Wong",""], ["Wong", "0143213123"], ["Ali", "0177213123"], ["Ali", "0177213123, 0124545345"], ["Ali", ""], ["Imran", "0133454335"]];

var uniqueData = arr.reduce((result, [name, number]) => {
    if(!result[name] || number.trim().length) result[name] = number;
    return result;
}, {});

console.log(Object.entries(uniqueData))

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

Establishing a Table of Disarray

I've hit a roadblock and I'm feeling confused about where to go next. Currently, I'm exploring the use of JavaScript to create tables for my data and display them in HTML. While I've successfully created the HTML table, I'm facing ...

What steps can be taken to identify the two highest numbers in an array, one being positive and the other

Seeking the optimal solution to resolve this issue Issue: Develop a function called ArrayChallenge (Javascript) that takes a single argument "arr" representing an array of numbers. The function should return the string true if there exist two numbers in t ...

Retrieving data from an external PHP script

I'm facing an issue with retrieving results from a PHP file after submitting a form: index.php (located at ) <form id='loginForm' action='http://domain1.com/mail.php' method='POST'> <input id=&apo ...

Modifying the appearance and behavior of an element dynamically as the page is being loaded using AngularJS

Struggling with a challenge for two days now, I have attempted to implement a panel-box using bootstrap and AngularJS. Within the confines of a controller, my code looks like this: <div id="menu2a"> <div class="panel list-group"> <div ...

Converting Image to Base64 String and Parsing into a JSON Object

Hey there, I'm currently working on creating a form where users can input their information along with an image. My goal is to send all this data together in a JSON object back to the Node.js server. In order to include the image, I've been attem ...

Is it possible to retrieve the complete HTTP response text using Node.js from a HTTP module's .get response?

I have a straightforward web server set up: const ws = require('http'); ws.createServer( function(req,res) { console.log('request received'); res.write('Hello world'); res.end(); }) ...

In nodejs, I am looking to update a specific string in numerous file names

I need to update a specific string in file names. Using glob and path, I'm able to extract multiple file names from various directories. Now, my goal is to rename these files from abcd-change-name.js to abcd-name-changed.js. Here's the progress ...

C# implementation of the btoa function from JavaScript

I am in need of assistance recoding a JavaScript function to C# that makes use of the btoa method to convert a string of Unicode characters into base64. The challenge lies in ensuring that the encoding used in both languages is identical, as currently, the ...

Tips for monitoring the activities of a different user on a website

I am working on a project where I need to display all the activities of one user to another user on a web page. Essentially, the second user should be able to see everything that the first user is doing on their page. While I know it can be done using AJA ...

encountering an issue with the react hook useHistory leading to an error

I recently encountered an issue while implementing useHistory() in my code. Previously, I had used it without any errors, but now I'm getting the following error in this component: Line 6:18: React Hook "useHistory" is called in function "showPost" ...

Override children component class names with Material UI Tooltip Component

Check out this example In this scenario, there are three visible buttons. The first button lacks a tooltip and changes color based on state and hover. The second button includes a tooltip but encounters issues with the className being overwritten, result ...

The date-picker element cannot be selected by html2canvas

I'm encountering an issue with Html2canvas while trying to capture a screenshot of my page. Specifically, the date shown in the date-picker on the page is not appearing in the screenshot. Do you have any insights into why this might be happening and h ...

Error in Typescript persists even after short-circuit evaluation is used

Kindly review the provided code sample type type1 = string[] | undefined; let variable1 : type1 = undefined; console.log(variable1 && variable1.length); Upon attempting to run this code in Typescript Playground, an error is generated stating Pro ...

How can I retrieve an updated object array within an extended class in JavaScript?

Hey everyone, I am new to working with ES6 classes. Currently, I am trying to inherit an initialized object (this._obj) with updated data in the class B, but I am encountering an issue where I am getting the length of the initialized object instead of the ...

What is the best way to sift through an array containing arrays?

Looking for help with filtering and pushing data from a JSON array? Specifically, I need to filter arrays where the data's attrs property includes a src attribute. It's proving challenging for me, so any assistance would be greatly appreciated. ...

A guide on updating an item in a basic JavaScript file with Node.js

This query pertains to Workbox and Webpack, but no prior knowledge of these libraries is necessary. Background Information (Optional) Currently using the InjectManifest plugin from Workbox 4.3.1 (workbox-webpack-plugin). While this version provides the o ...

Unable to transform Symbol data into a string - Error when making a React AJAX delete call

I'm encountering an issue where I am getting a Cannot convert a Symbol value to a string error in the console. My tech stack includes React v15 and jQuery v3. https://i.stack.imgur.com/qMOQ8.png This is my React code snippet: var CommentList = Reac ...

Using the ui-router to repeatedly call an AngualrJS directive

I've encountered an issue with my HTML audio player in AngularJS. When the page is refreshed, everything works perfectly - I can set the source and play audio without any problems. However, if I navigate to another state in the app and then try to loa ...

Access an external URL from JSON data simply by utilizing VueJS

I am currently facing a challenge with linking to external URLs. The URL is extracted from JSON and connected to an HTML tag, but I am unable to retrieve the data and link it to the URL when clicking on images. HTML <section class="bg-light page-secti ...

Formatting JSON data as HTML

When acquiring JSON data, I utilize the following code snippet: $.getJSON( "data.json",function foo(result) { $.each(result[1].data.children.slice(0, 10), function (i, post) { $("#content").append( '<br> HTML <b ...