How to remove duplicate object from array in JavaScript - javascript

I am working on an array, Actually, I have a dropdown list. I am pushing that object into an array but I am facing one issue actually when I select something it shows two elements at the same time like in dropdown let suppose if I have options ( option1, option2, option3). For example, I have selected option1 it pushed object value as option1 but when I select option2 it also pushed it into an array. I want unique values like if I select options2 it should be select recent value.
generateExtraFieldData = (data, name, index, type, value, values) => {
const { projectFloorData, unitModifiedData } = this.state
let obj = projectFloorData[name]
obj['data'] = data
let tempArr = [...unitModifiedData]
tempArr.push(obj)
this.setState({ unitModifiedData: this.uniqueFiles(tempArr) })
// projectFloorData[name].data = data
}
uniqueFiles = (data) => {
let unique = _.uniqBy(data, 'index')
console.log('## array', unique)
return unique
}
I have used lodash but it just return ist selected value, I need a recent value like if the user selected a second time

Try using yourArray.length = 1;, this limit you array to an int limit. And if you select another option, just do yourArray.length = 0 to clear the array and then again yourArray.length = 1; to store the new option.

why are you pushing your selected value into your array if you want to select a single value at a time try an object instead of an array and change the value/ reassign the value on selection.

Related

How to remove one value from a key in localstorage that has many values?

I've seen this question asked before but the solutions didn't help me hence why i've asked it again.
Currently, I am storing values into an array and that array is getting stored into localstorage.
This is the object
data.items -
0: {id: 190217270, node_id: 'MDEwOlJlcG9zaXRvcnkxOTAyMTcyNzA=', name: '3-Bit-CNC-Starter-Pack'}
1: {id: 187179414, node_id: 'MDEwOlJlcG9zaXRvcnkxODcxNzk0MTQ=', name: 'inb-go}
I have mapped through this and used 'name' as the value. I am calling this value through a button using this function
const favs = [];
function checkId(e) {
if (e.target.value !== ""){
if (!favs.includes(e.target.value)){
favs.push(e.target.value);
localStorage.setItem("name", JSON.stringify(favs));
console.log(favs);
document.getElementById("favsarray").innerHTML = favs;
}
}
}
and to remove the value from localstorage I am using this function.
function removeId(e, value) {
if (e.target.value !== "") {
favs.pop(e.target.value);
console.log(favs);
document.getElementById("favsarray").innerHTML = favs;
const stored = JSON.parse(localStorage.getItem("name"));
delete stored[value, e.target.value];
localStorage.setItem("name", JSON.stringify(stored));
console.log(stored);
}
}
Although the value is being removed from the array, it is not being removed from localstorage.
side note - I am calling this function with a separate button.
console log
array (item is gone)
[]
localstorage (the value is still there)
[
"Spiral-Up-Cut-Router-Bit"
]
But if I select another item to be added to localstorage, then the previous item gets removed.
UNFAVORITE - FUNCTION REMOVEid
[
"Spiral-Up-Cut-Router-Bit"
]
NEW FAVORITE - FUNCTION NEWId
[
"graphqless"
]
I hope this makes sense, I tried to add detail to it as best as possible.
Try to use localStorage.removeItem method to remove item from storage:
function removeId(e, value) {
if (e.target.value !== "") {
favs.pop();
// other code here
localStorage.removeItem('name'); // method to remove item from storage
}
}
UPDATE:
If an item is removed from array and we want to set this updated value to localstorage, then we can just update this value:
function removeId(e, value) {
if (e.target.value !== "") {
favs.pop();
console.log(favs);
document.getElementById("favsarray").innerHTML = favs;
const stored = JSON.parse(localStorage.getItem("name"));
delete stored[value, e.target.value]; // this code looks very fishy - charlietfl
localStorage.setItem("name", JSON.stringify(favs));
console.log(stored);
}
}
The easiest way is to just overwrite the item in localStorage. Once you remove the item from the favs array, call localStorage.setItem("name", JSON.stringify(favs)); again and you're done.
I am not sure whether this will help you but anyway I am sharing.
I don't understand this part of the abovementioned code:
delete stored[value, e.target.value];
What are you passing in the value and e.target.value? If it is the name ("Spiral-Up-Cut-Router-Bit") itself then the delete won't remove the value from the array. Usually, when you use the delete operator on the JS array you need to pass the index of the value, not the value itself.
Also, When you delete an array element, the array length is not affected. This holds even if you delete the last element of the array.
When the delete operator removes an array element, that element is no longer in the array.
You can refer to the above output image, when I deleted the array values using the value even though its output is true it does not delete the value from the array. But when I used the index value for the delete, it deleted the value from the array.
Note: The array just removed the value but did not clear the index.
Maybe, you should use splice to remove specific values from the array and store the new array into the storage.
Also, the delete operator works well with JS objects. If you want to read more about this you can go to this link.✌🏼
Delete using splice:
var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple']; trees.splice(3,1); console.log(trees);
As suggested, use splice (which will also update the Array's length) to delete the entry from the Array.
const stored = JSON.parse(localStorage.getItem("name"));
const index = stored.indexOf(nameValue);
if (index !== -1) {
stored.splice(index, 1);
localStorage.setItem("name", JSON.stringify(stored));
}
See:

Filter an array based on another array. (Using React)

The goal is to filter an array based on the slots the user has selected.
For example an array has slots for 7pm-9pm,10pm-12pm and so on.
Now the user selects 7pm-9pm, so now I want to filter the array which have 7ppm-9pm or is the users wants
7pm-9pm and 10pm-11pm so the data should be based on 7pm-9pm and 10pm-11pm
Here is how I store the values
This is the original array
data :[
{
name:"something",
phone:"another",
extraDetails : {
// some more data
slots : [
{item:"6PM-7PM"},
{item:"7PM-8pm}
]
}
},{
// Similarly more array with similar data but somewhere slots might be null
}
]
Now for example we have this array
slots:[{6PM-7PM,9PM-10PM,11PM-12AM}]
Now this should filter all those which includes timeslots of 6PM-7PM,9PM-10PM,11PM-12AM
or if the user selects
slots:[{6PM-7PM}]
We should still get the results that includes 6pm-7pm more or else don't matter.
First, I'd suggest using this for your slots representation for simplicity, but you can alter this approach depending on your actual code:
slots: ['6PM-7PM', '9PM-10PM', '11PM-12PM']
Then you can iterate through your data and use filter:
const querySlots = ['6PM-7PM', '9PM-10PM', '11PM-12PM'];
const matchedPersonsWithSlots = data.filter( (person) => {
let i = 0;
while ( i < person.extraDetails.slots.length ) {
if (querySlots.includes(person.extraDetails.slots[i]) return true;
i += 1;
}
return false;
});
matchedPersonsWithSlots will then have all the people that have a slot that matches one of the slots in your query, because if any of the query slots are in a person's list of slots, then it's included in the result set.
EDIT to include a different use case
If, however, every slot in the query array must be matched, then the filtering has to be done differently, but with even less code.
const matchedPersonsWithAllSlots = data.filter(person =>
querySlots.every((qSlot)=>person.extraDetails.slots.includes(qSlot)));
The above will go through each person in your data, and for each of them, determine whether the person has all of your query slots, and include them in the result list, only if this is true.

How to return the values of selected options using JS filter function

I would like to get a an array returned of the values of the selected option.
I would like to use Array.prototype.filter.
I can get the filter to return an array of selected options but not an array of the value of the options. Is there a method to return an array of the value of the selected options.
I can get an array of the values using forEach or a for loop but not the filter function. If this is not possible I would like to know the reason.
Select with the values
<select
multiple
className="form-control"
id="genre"
onChange={handleGenreChnage}>
<option>drama</option>
<option>music</option>
<option>adventure</option>
<option>historical</option>
<option>action</option>
</select>
Function using filter - returns option not the value from option.
const handleGenreChnage = (event) => {
const { options } = event.target;
const optionsArray = [...options];
const values = optionsArray.forEach((option) => {
if (option.selected) {
return option.value;
}
});
setForm({ ...form, genre: values.toString() });
};

How to add only unique options to datalist element?

I am trying to fetch a set of objects from a server and add their attributes as options to a datalist element whenever a user clicks on the input field. I want to display unique options in the list only, however, anytime the input field comes into focus, my code will keep adding every option to the datalist even though I am making a check for it not to do so.
<form action="">
<label for="">Step 1: Select or create a theme: </label>
<input type="input" list="themes" name="themes" onfocus="fetchThemes()" />
<datalist id="themes">
</datalist>
</form>
<script>
let host = "http://localhost:3002"
function fetchThemes(){
fetch(host + "/contents")
.then((response) => response.json())
.then((data) => addToDatalist(data))
}
function addToDatalist(data){
let datalist = document.getElementById('themes');
for (let object of data){
let option = document.createElement("option")
option.value = object.name
if (datalist.contains(option) === false){
datalist.appendChild(option)
}
}
console.log(document.getElementById('themes'))
}
</script>
I know i'm missing something small, but im not sure what it is that i'm doing wrong. Are DOM elements similar to objects in Python or Java, where even though two objects can have the same values, they're considered different since they are stored in separate memory locations? How can I go about fixing this?
i have made two arrays, first one is the check the array which contains all the unique values and the second one is the response of the server "object".
here i am comparing all the values of the check array with the one value of the object to get the unique value !!!
i hope this helps you !!!
//consider object as an array of the options and you want to include only the unique one
var check = []
var object = []
for(const i=0;i<=object.length;i++)
{
for(const j=0;j<=check.length;j++)
{
if(check[j] ===option[i])
{
console.log("Value exists")
}
else{
option.value = check[j]
}
}
}
for(const i=0;i<=check.length;i++)
{
option.value = check[i]
}

Filtering array based on checkbox conditional values

So, I'm a bit stuck. I'm filtering an array based on the values of another array. When the user clicks a check box a year value gets pushed to an array (checkedBoxes), then the yearMarker array is populated from meeting the condition IF the marker.year (from mapMarkers array) entry is equal to any value in the CheckedBoxes array. This then gets passed to the getMarkers function which populates the map I'm working on. This all works perfectly. However when I click uncheck the box it doesn't work. If I log the checkedBoxes array I can see that the year is being removed as it should. The code to populate/replace yearMarkers is the same as the checked state, as with the function to create map markers. Yet it doesn't work. Any help to straighten out my thinking on this would be appreciated.
subFilter.forEach(item => {
const elm = item;
item.addEventListener('click', function () {
if (elm.checked) {
markersLayer.clearLayers();
checkedBoxes.push(elm.value);
yearMarkers = mapMarkers.filter(marker => checkedBoxes.includes(marker.year));
getMarkers(yearMarkers, markersLayer);
} else{
checkedBoxes = checkedBoxes.filter(entry => entry !== elm.value);
yearMarkers = mapMarkers.filter(marker => checkedBoxes.includes(marker.year));
getMarkers(yearMarkers, markersLayer);
console.log('unchecked');
console.log(checkedBoxes);
}
})

Categories