Eliminating duplicate negative values in an array

Let's consider the following array:

var arr = [-1, -5, 4, 5, 3];

If we want to remove any negative numbers from the array, resulting in an output like this:

[-1, 4, 5, 3]

Answer №1

This function will eliminate any negative numbers in an array that also have a corresponding positive number

var arr = [-1, -5, 4, 5, 3, -5];

arr = arr.filter(function(a, b){
  if(a < 0 && arr.indexOf(-1*a) > -1){
    return 0;
  }
  if(a < 0 && arr.indexOf(a) != b){
  return 0;
  }
  return 1;
})

console.log(arr);

Answer №2

To implement a custom filter function, you can utilize the filter() method along with Math.abs().

var array1 = [-2, -6, 6, 7, 8];
var array2 = [-2, -6, -6, 7, 8];

function specialFilter(array) {
  return array.filter(function(element) {
    if (element > 0) return true;
    else {
      var absoluteValue = Math.abs(element);
      if (array.indexOf(absoluteValue) != -1) return false;
      else return !this[element] ? this[element] = 1 : false;
    }
  }, {})
}

console.log(specialFilter(array1));
console.log(specialFilter(array2));

Answer №3

To find unique values in an array, you can loop through the array and add elements that are not duplicates based on their absolute value:

var uniqueValues = [];
arr.forEach(function(item) {
    if (!uniqueValues.includes(Math.abs(item)) && !uniqueValues.includes(item)){
        uniqueValues.push(item);
    }
});

This approach was inspired by a similar solution found in this post on Stack Overflow.

Answer №4

Always remember to verify the sign or if the absolute value is omitted.

let numbers = [-2, -7, 6, 7, 5],
    output = numbers.filter((num, _, nums) => num >= 0 || !nums.includes(Math.abs(num)));
    
console.log(output);

Answer №5

Eliminate Negative Numbers

var numbers = [3, -4, 7, -2, 1, 6, -2];

console.log(removeNegatives(numbers));

function removeNegatives(numbers){
  return numbers.filter((num) => {
    if( num < 0 && numbers.indexOf(Math.abs(num)) != -1){
      return false;
    } else {
      return num;
    }
  })
}

Answer №6

Check out this alternative approach to removing duplicates without the need for repetitive indexOf. I found inspiration in a previous post that introduced the uniq function, which eliminates duplicate elements from an array. In addition, I made sure to remove negative values if their positive counterpart already exists in the array.

var arr = [-1, -5, 4, 5, 3];

function uniq(a) {
    var seen = {};
    return a.filter(function(item) {
        return seen.hasOwnProperty(item) ? false : (seen[item] = true);
    });
}

function preRemoveNegatives(a) {
  let table = {};
  a.filter(e => e >= 0).forEach(e => table[e] = true);
  return a.filter(e => e >= 0 || !table[-e]);
}

console.log(uniq(preRemoveNegatives(arr)));

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

Which is more cost-effective: using Array.filter or a loop?

Is using the filter function in the Array cheaper than a typical for loop? If it is, what makes it more cost-effective? ...

now.js - There is no method in Object, however the click event works in jQuery

Here is a simple NowJS code snippet for the client side: $j(document).ready(function() { window.now = nowInitialize('http://xxx.yyy:6564'); now.recvMsg = function(message){ $j("body").append("<br>" + message); } $ ...

Is the epoch date format not compatible with the ngx bootstrap datepicker?

Consider this scenario: Jun 13, 2003, 23:11:52.454 UTC represented in epoch date format as 1055545912454. However, when I input this value as bsValue, I receive undefined. Objective My goal is to send the date in epoch format when making a server request ...

Nuxt Fire / Firebase Vuex does not recognize $fireDb

Currently, I am utilizing Nuxt JS 2.9.2 for constructing a Javascript application. The application incorporates Firebase integration through the Nuxt Fire module, as well as Vuex for managing state and authentication. The project has been successfully con ...

Mapping custom colors to paths in D3 Sunburst visualizations can add a vibrant and unique touch

Currently, I am in the process of developing a D3 Sunburst Vue component and utilizing the npm package vue-d3-sunburst for this purpose. To access the documentation for the package, please visit: https://www.npmjs.com/package/vue-d3-sunburst The document ...

Tips for dividing and locating the final index in Google Sheets

Is there a way to accomplish this in Google Sheets? tag_name A_B_C C A_B_C_D D I have been using the following formula: =INDEX(SPLIT(B2, "__"), 0, 3) My goal is to automatically select the last index of the values returned by the split fu ...

Node 19820 threw an uncaught promise rejection warning due to a TypeError stating that it cannot read the property 'byteLength' of an undefined value

I'm currently working on developing an API with the use of Express to enable the upload of images to Firebase storage. However, whenever I try to access this particular endpoint, an error message is displayed: "(node:19820) UnhandledPromiseRejectionWa ...

Executing Basic Authentication in Javascript through window.open()

After a user logs into my app, they have the option to download a CSV file from the server by clicking on a button. The URL for the download is secured with basic authentication. When attempting to open the URL using the code below: window.open('http ...

Utilizing asynchronous programming for scenarios where two requests need to be sent, with the response from the first request being required for the second request

I have an async function that looks like this: exports.myFunction = async (req, res, next) => { if (some condition) { next() } try { const results = await axios.get(`https://a-domain.com/url/path`); const info = results.data; c ...

Leveraging jQuery and Ajax for retrieving information from a JSON document

As a newcomer to JS, I have successfully set up a JSON file on my Express server. My code snippet looks like this: const data = require('./src/data.json') app.get('/search', function (req, res) { res.header("Content-Type",'app ...

What is the best way to transform a text file into an array of objects?

I have a text that resembles the following structure: {"age": "52", "id": 1, "name": "Hulk"} {"age": "33", "id": 2, "name": "Iron Man"} My goal is to parse ...

Unable to navigate using single-page navigation due to JavaScript malfunction

I'm struggling with this particular code and I'm hoping for some assistance. My experience with javascript is limited, so I'm reaching out for help instead. I am trying to implement the jquery single.page.nav feature that enables navigation ...

Encountering an issue while attempting to input a URL into the Iframe Src in Angular 2

When I click to dynamically add a URL into an iframe src, I encounter the following error message: Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'SafeValue%20must%20use%20%5Bproperty%5D' To ensure the safety of the ...

Using jQuery to animate a DIV sliding in from the side

When a user scrolls down (x) pixels, I'm smoothly sliding a DIV into the viewport horizontally. If the user scrolls back up, the DIV scrolls out again. However, the sliding motion appears jerky and pauses at certain moments. <div id="doom_o">&l ...

a class instance in Java Script returned as undefined

Having sought resolution for this question once before, I find myself revisiting it as the issue still persists. My apologies for the duplicate post. The first file in question is block.js: class Block{ constructor(timeStamp, lastBlockHash, thisBloc ...

Exploring Unanchored Substring Queries in Loopback API

Searching for a solution to implement a basic substring query using the loopback API for a typeahead field. Despite my efforts, I have not been able to find a clear answer. I simply want to input a substring and retrieve all brands that contain that subst ...

What is the best way to link several items to a different class or object?

In the task at hand, I am tasked with creating a software program that simulates a zoo environment with three specific types of animals: giraffes, tigers, and penguins. A crucial aspect of this program is to develop a method that effectively assigns these ...

What is the method to determine the duration of a video using the FileReader function to access the video file?

My current challenge involves uploading a video to a server and reading it on the client end using `readAsBinaryString()` from FileReader. However, I am facing an issue when trying to determine the duration of this video file. If I attempt to read the fi ...

Insert elements to an XML document in Node.js using libxmljs

I've been working on updating an XML file by adding a new child node using the code below: var libxml = require('libxmljs'); var xml = '<?xml version="1.0" encoding="UTF-8"?>' + '<root>' + ...

Using the # symbol alongside other characters or numbers may prevent Reg Ex from validating

I am asking the same question again as I did before. I apologize, but I have checked all the links provided and they were not helpful. Also, this is my first time asking a question here so I was not very clear on how to ask. Here are the details of my iss ...