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]
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]
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);
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));
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.
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);
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;
}
})
}
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)));
Is using the filter function in the Array cheaper than a typical for loop? If it is, what makes it more cost-effective? ...
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); } $ ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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>' + ...
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 ...