Need to remove the delItem from the toDos array not sure how - javascript

I can't figure out how to complete this function. I have filtered through to find the variable that matches the id but now I need to match that item to the delItem var and delete it.
function deleteToDo(tot) {
let delItem = toDos.filter((remove) => remove.id === tot);
/// i need to remove item from toDos array that matches delItem.
renderTheUI(toDos);
}

Array#filter returns an array, with all items that match the predicate. Instead of getting the item that you want to remove, get an array without the item by checking that the id is not equal to tot. Then use the filtered array in renderTheUI:
function deleteToDo(tot) {
const filteredToDos = toDos.filter((item) => item.id !== tot);
renderTheUI(filteredToDos);
}
I would suggest moving the call to renderTheUI out of the deleteToDo method, since it might be very confusing. The deleteToDo will return an updated array, and then you can render the new array:
function deleteToDo(tot) {
return toDos.filter((item) => item.id !== tot);
}
const filteredToDos = deleteToDo(2);
renderTheUI(filteredToDos);

You do not need to find the element with filter but its index in the array.
function deleteToDo(tot) {
let delIndex = toDos.findIndex((remove) => remove.id === tot);
if (delIndex !== -1){ // if element was found
toDos.splice(delIndex,1); // remove the element from the toDos array
}
renderTheUI(toDos);
}

Related

get the index of two elements and manipulate the array accordingly

I build an array with the following code:
var intestColonne = [];
$('.tbi').find('tr:first th').each(function(){
intestColonne.push(($(this).children('select').val()));
});
//intestColonne=intestColonne.pop(); //if this row is parsed the array becomes undefined
Now I want to check if there are multiple entries of a specific value in the array:
if(intestColonne.filter(x => x === "importo").length>1){
//check the index of each "importo" element
//store it into variables
//remove all the other "importo" leaving only the first (lowest index)
}
I am stuck at the first step since I haven't found a specific function that may return all the indexes of the "importo" value.
indexOf will return the first index, lastIndexOf will return the last. Using indexOf I can specify where to start looking from but this will hardly satisfy my goal.
Isn't there another type of search I can use?
You can use map to get the indexes of the elements before filter.
intestColonne.map((x, i) => x === 'importo' ? i : null).filter(x => x != null);
Alternatively, use Array#reduce.
intestColonne.reduce((acc, curr, i) => {
if (curr === 'importo') acc.push(i);
return acc;
}, []);
You can use the .map() method to create an array of all the indexes of a specific value in the array. Here is an example:
var importoIndexes = intestColonne.map((value, index) => value === "importo" ? index : '').filter(String);
This will create an array importoIndexes containing all the indexes of the value "importo" in the intestColonne array.
You can then use the .slice() method to remove all the other "importo" leaving only the first (lowest index)
intestColonne = intestColonne.slice(0, importoIndexes[0]).concat(intestColonne.slice(importoIndexes[0] + 1));
Javascript array filter method's second argument supplies index of an element. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
So you can get index of first element using indexOf and then filter it:
const index = intestColonne.indexOf("importo");
const result = intestColonne.filter( (o,i) => o !== "importo" || i === index );

Find and Change specific item from an object array

I'm dealing with an array like
arr = [{id:'first',name:'John'},{id:'fifth',name:'Kat'},{id:'eitghth',name:'Isa'}]. Now i want to give condition to the array like if i get id 'fifth' in array, The array will change to
arr = [{id:'first',name:'John'},{id:'sixth',name:'Kat'},{id:'eitghth',name:'Isa'}]
Like just one part of an item is modified. How can i do that in js?
You can use Array.prototype.find to locate the entry, and then simply update its id attribute:
const arr = [{id:'first',name:'John'},{id:'fifth',name:'Kat'},{id:'eitghth',name:'Isa'}];
const entry = arr.find(item => item.id === 'fifth');
entry.id = 'sixth';
console.log(arr);
You can also use Array.prototype.findIndex to retrieve the index of the entry that you want to replace, and modify it accordingly:
const arr = [{id:'first',name:'John'},{id:'fifth',name:'Kat'},{id:'eitghth',name:'Isa'}];
const targetIndex = arr.findIndex(item => item.id === 'fifth');
arr[targetIndex].id = 'sixth';
console.log(arr);
However, the two methods above only help to find the first matching element. If you have multiple entries in the array with the ID of fifth, then you are better off using iteration:
const arr = [{id:'fifth',name:'Kat'},{id:'fifth',name:'Kat'},{id:'fifth',name:'Kat'}];
arr.forEach(item => {
if (item.id === 'fifth') {
item.id = 'sixth';
}
});
console.log(arr);

Deleting a particular element from an array

state = { filters: ['all'] }
this.state.filters.includes('humans') ?
this.state.filters.filter(val => val !== 'humans') : this.state.filters.push(dropdown)
I'm using a condition such that, when I click on a button the item('humans') gets pushed to state and when I click on the same button again I need to remove the item('humans') from the array. Push is working fine, I need help in removing it. I used filter like the above code , it does not get added again to the array but also not removing.
Thanks in advance.
Use:
let index = this.state.filters.indexOf('humans');
if (index !== -1)
this.state.filters.splice(index, 1);
Or you better follow this approach to avoid mutating the state in React:
let array = [...this.state.filters]; // make a separate copy of the array
let index = array.indexOf('humans')
if (index === -1) { // not in the array
array.push('humans');
this.setState({filters: array});
} else { // exists in the array
array.splice(index, 1);
this.setState({filters: array});
}
To remove an element from array, You can do below thing
filters.splice(index_of_the_val, 1);
You shouldn't modify the state with the push, 'cause it might not trigger the re-rendering. You should use the setState method.
toggleFilter = filter => {
const isIncluded = this.state.filters.includes(filter)
const add = (filters, filter) =>
filters.concat(filter)
const remove = (filters, filter) =>
filters.filter(f => f !== filter)
this.setState(prevState => ({
filters: isIncluded
? remove(prevState.filters, filter)
: add(prevState.filters, filter)
}))
}

How to setState to update an array in React?

I need to update an array in the state of my component in React.
I've seens several topic with this question, but so far all of them are adding new items to the array with the spread operator, but I need to add OR remove items on a callback like this:
handleCheck (newStatus, isChecked) {
this.setState({ filterStatus: [...this.state.filterStatus, newStatus] })
}
But the problem here is that it didn't work for status where the isChecked boolean comes false to remove them from the array
What is the best way to add or remove items from that array, hopefully with spread operator?
Thanks
try to use the .filter to remove the element. Remember to duplicate the array (using [...array] syntax) before using .filter, to don't change the original array:
handleCheck (newStatus, isChecked) {
let newArray = isChecked? // if isChecked is true
[...this.state.filterStatus, newStatus] : // add element
[...this.state.filterStatus].filter(e => e !== newStatus); // remove the elements that are equal to newStatus
this.setState({ filterStatus: newArray})
}
Think it functionnal !
const prevArray = this.state.array;
const itemsToAdd = [item, item, item];
//this function map the prev array escaping elements to remove
//and then push itemsToAdd to the new array
const updateArray = ( i = [0], newArray = [] ) =>
i < prevArray ?
yourRemovingCondition(prevArray[i]) ?
updateArray( i + 1, newArray )
: updateArray( i + 1, [...newArray, prevArray[i])
: [...newArray, ...itemsToAdd]
;
setState({array: updateArray()];
Put the check, add the element only when the bool isChecked is true, otherwise use filter to remove the element from the array.
Like this:
handleCheck (newStatus, isChecked) {
this.setState(prevState => {
let filterStatus;
if (isChecked) {
filterStatus = [...prevState.filterStatus, newStatus];
} else {
filterStatus = prevState.filterStatus.filter(el => el.id !== newStatus.id)
}
return { filterStatus }
})
}
Note: In place of id in filter callback method use the correct unique property name.

How to filter an array with another array in React Native?

So I am basically trying to say "give me all added items that were not actually added to the cart" with my filter function below. If any of the addedItems product ids cannot be found in the cartItems ids then it should return those items. But instead unaddedCartItems is an empty array when I know there are addedItems ids that are not the same as any of the cartItems ids. Do anyone know how to achieve this?
const unaddedCartItems = addedItems.filter((addedItem) => {
cartItems.forEach((cartItem) => {
return cartItem.id !== addedItem.productId;
});
});
It's because your return is nested under forEach and you aren't returning that value in your filter. Instead, use find:
const unaddedCartItems = addedItems.filter( addedItem => {
return !cartItems.find( cartItem => cartItem.id === addedItem.productId );
});
find loops through an array until it finds a matching item. This means that if it finds the id in cartItems, it will immediately stop the loop and return the item.
Would using some work here?
const unaddedCartItems = addedItems.filter((addedItem) =>
!cartItems.some(cartItem => cartItem.id === addedItem.productId);
because your return is nested under forEach and you aren't returning that value in your filter

Categories

Resources