Eliminate redundant entries from an Ionic3 array

Looking for a solution to eliminate duplicate values in the storage array within Ionic3

this.storage.get('thestations').then((val) => { 

           for(let i =0;i<val.length;i++){
            if(this.newarray.indexOf(this.newarray) == -1) {
            this.newarray.push(val[i]);
            } 
                console.log(newarray);

      });

Despite the efforts, duplicates are still being returned

Answer №1

Utilizing Set Method

let fruits = ["Banana", "Orange", "Apple", "Mango", "Mango"];
let uniqueFruits =  Array.from(new Set(fruits));

Verification using Reduce Function

let fruits = ["Banana", "Orange", "Apple", "Mango", "Mango"];
let uniqueFruits = fruits.reduce(function(result, element) {
    if(result.indexOf(element)==-1)
       result.push(element);
return result;
}, [])

Answer №2

Quick summary:

[...new Set(["Grapes", "Pineapple", "Kiwi", "Watermelon", "Watermelon"])]

this.data.retrieve('thecities').then(data => {  
  console.log('original list', data);   
  console.log('unique values', [...new Set(data)]);
})

Answer №3

Whether or not you have already found a solution to your problem, I am here to offer you one of the most effective answers.

When it comes to Javascript, we have access to the powerful lodash library. For detailed information, please check out the Lodash Documentation

Lodash is packed with numerous built-in functions such as filter, unique, isEqual, and many more.

Step 1: Start by installing the npm package for lodash using the following command.

npm install lodash --save

Step 2: Next, import the dependency into your component file.

import * as lodash from 'lodash';

Step 3: Imagine you have an array named abcArr = [5,10, 8, 11, 10, 8]; And you want to remove all duplicate numbers.

Simply use the code snippet below to achieve the desired outcome.

let abcArr = [5,10, 8, 11, 10, 8];
let uniqueArr = []; 
uniqueArr = lodash.uniqWith(abcArr, lodash.isEqual);

This will provide you with the solution you are looking for. Hopefully, this helps!

Answer №4

To achieve this, you will need to utilize a function similar to the one shown below

var values = ["Banana", "Orange", "Apple", "Mango", "Mango"];
var newArray = [];

for(let i=0; i < values.length; i++)
{
    if(newArray.indexOf(values[i]) == -1)
        newArray.push(values[i]);
}
console.log(newArray);

</script>

Remember, you can personalize the values variable based on your specific needs.

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

The click event for getelementbyid() function is malfunctioning

I need assistance with a website I am creating that plays audio when a certain condition is met. Specifically, I want the audio to play if x falls within a specific range of numbers, but also continue playing if x does not fall within that range after th ...

As time passes, the Azure Service Bus Consumer experiences a decline in performance

My issue involves managing different topics with subscriptions, each tied to a consumer. Over time, I've noticed a decline in the number of messages received. Despite trying to utilize maxconcurrentcalls, it seems to only be effective at the start. My ...

What is the best way to transform this PHP Object into an array?

I am working with a Javascript array that needs to be passed to a PHP script using Ajax. Inside file.js: var params = {}; params["apples"] = "five"; params["oranges"] = "six"; params["pears"] = "nine"; var ajaxData = {data : params}; fetchData(ajaxData); ...

I'm struggling to understand how to interpret this. The v-tab function seems to be generating a button with various properties, but I'm unsure which specific property is related to

The V-tab below generates the button known as the right one on the v-app-bar: https://i.stack.imgur.com/DzNmq.png <v-tab :to="'/demo'" active-class="text--primary" class=&quo ...

Utilize getElementsByClassName to dynamically alter the appearance of specific elements upon triggering an event

I'm attempting to utilize onmouseover="document.getElementsByClassName().style.background='color'" in order to switch the color of all divs with a specified classname to a different color when hovering over another element on the page. ...

How to Make Buttons Vanish and Reappear

Check out this fiddle for a picture button 'scroller' that I created. It may not be perfect, but my main focus is on making the arrow buttons fade in and out when reaching the end of the picture order. I am considering using a JavaScript functio ...

Nesting promises is proving to be successful while Promise.all is currently not functioning as

My directive contains the following code structure: myApp.directive('myDirective', function(s1, s2, s3) { return { restrict:'E', link: function($scope,) { s1.then(function(data) { $scope. ...

Show the selected checkbox options upon clicking the submit button

Having trouble setting up a filter? I need to create a feature where checked values from checkboxes are displayed in a specific div after submitting. The display should include a 'Clear All' button and individual 'X' buttons to remove e ...

What is the best way to delete an item from a React array state?

In my Firebase database, I have an array stored under the root branch called Rooms. Within the app, there is a state named rooms which is also an array. I successfully set it up so that when a user enters a new room name and submits it, it gets added to th ...

Node.js video tag requests minimal data transfer on mobile devices

After creating a node server for streaming mp4 videos from a Mongo database using gridfs, I encountered an issue. The videos stream perfectly to desktop browsers, but when attempting to stream to a mobile device, the video player shows up, but the video do ...

How can I automatically redirect a React page once I receive a response from Express?

I'm facing an issue with redirecting from one page to another in React. The setup involves an Express server serving the required data to React, and upon receiving the data in React, the goal is to display that result on another page by triggering a r ...

PHP is unable to retrieve the formData object sent via ajax

I've been experimenting with sending a formData object to PHP (I'm following a tutorial at this link), but I'm encountering some obstacles. Firstly, I create the formData object and fill it with: var formdata = new FormData(); formdata.appe ...

How can I write an if-else statement in JavaScript with Mongoose for MongoDB?

I am facing a challenge where I need to execute a statement only if the object is not null. If the object is null, I should skip executing anything. Is there a correct way to achieve this? I attempted it on MongoDB Playground but unfortunately, it did not ...

Having trouble retrieving PHP variable values using JavaScript?

<div id="div01">01</div> <div id="div02">02</div> <img src="../img/logo.png" onclick="blueSky()"/> js function blueSky() { $.ajax({ type:'GET', url: 'test.php', success: function(respond) { document.ge ...

Saving changes made in HTML is not supported when a checkbox is selected and the page is navigated in a React application using Bootstrap

In my array, there are multiple "question" elements with a similar structure like this: <><div className="row"><div className="col-12 col-md-9 col-lg-10 col-xl-10 col-xxl-10"><span>Question 1</span></div ...

Unexpected JSON token error occurs in jQuery when valid input is provided

I encountered an error that I'm struggling to pinpoint. The issue seems to be related to the presence of the ' symbol in the JSON data. After thoroughly checking, I am positive that the PHP function json_encode is not responsible for adding this ...

Is there a way to alter the timestamp on comments in a React Native app, similar to Instagram's functionality, using dayjs?

I am currently working on a project using react native in combination with dayjs library. My goal is to compare the timestamp of when a comment was written with the current time, and then display this compared time using console.log() with the help of day ...

Retrieving Identifiers with Typescript from an object

I'm a newcomer to Typescript and I'm looking to extract ids from an observable Here's the observable data: let myObj = [{ "id": 1, "text": "Mary" }, { "id": 2, "text": "Nancy" }, { "id": 3, "text": "Paul" }, { "id": 4, "tex ...

What is the best method for exporting a MapboxGL map?

I am currently utilizing mapboxGL to display maps on a website, and I am interested in exporting the map as an image with the GeoJSON data that has been plotted. I attempted to use the leaflet plugin for this purpose, but it was unable to render clusters ...

Setting up PostgreSQL database integration with Node.js

I want to remove certain entries from a PostgreSQL database based on creation/expiry dates, but I only want this to happen when the Node server first starts. Currently, I have added the line DELETE FROM ....db WHERE date <= CURRENT_DATE to the main r ...