Remove by index value from props array - javascript

I am trying to remove a value by Index of the props array passed from another component.
[...this.props.data].splice([...this.props.data].indexOf(oldData), 1)
const {tableData, ...application} = oldData;
this.props.deleteData(application);
It deletes the data, but not just the selected value, but both values at the same time. I guess the problem is in the splice..indexOf
oldData :is the selected row that needs to be deleted.

You need to concat from 0 to index - 1 and from index + 1 to length - 1. So a simple this.props.data.slice(0, index).concat(this.props.data.slice(index) + 1) Should work.
Imo concat is easier to read and reason about because it does not mutate your array.
A filter could also work for you:
const filterIndex = target => (_, i) => i !== target;
newData = data.filter(filterIndex(index));
To use the filter version is pretty easy, two ways, depending on the use case.
1) Remove a specific index without leaving holes in the array
const target = this.props.data.indexOf(oldData);
const newData = this.props.data.filter((_, index) => index !== target);
2) Remove a specific value from the array (all its occurrences) without leaving holes in the array
const newData = this.props.data.filter((data) => data !== oldData);
Those two are slightly different as the first one will only remove the first occurrence of oldData and the second all
occurrences.

Related

How to splice the specific index using the IndexOf method of javascript

I have module where I need to uncheck or check the data using checkbox. Now the problem is I need to slice the push value if the user uncheck it based on the target value. Currently when i try to console log the index it result -1 meaning: "it is not present" I will show you guys my sample code and sample attached image for the reference to make more detailed..
Code:
var array = [...this.state.checkboxVal];
console.log(e.target.value,"my index")
var index = array.indexOf(parseInt(e.target.value));
console.log(index);
if (index > -1) {
array.splice(index, 1);
await this.setState({ checkboxVal: array });
}
console.log(this.state.checkboxVal);
The Expected Output: The Index 1 should be remove
The problem is that you are storing an array of arrays so you are trying to compare number to array and apparently it will return -1. To solve this you can use findIndex function in the following way.
var value = parseInt(e.target.value);
var index = array.findIndex((element) => element[0] === value);
NOTE: Please use let and const these are latest way to define your variables.
The issue is that you are comparing incompatible types, "number" vs "array", so a match can never be found.
If you are simply wanting to remove an element from an array in state in React, using a Array.prototype.filter is a common pattern.
const targetValue = Number(e.target.value);
this.setState(prevState => ({
checkboxVal: prevState.checkboxVal.filter(([val]) => val !== targetValue),
}));
The filter callback ([val]) => val !== targetValue is taking the array element and uses destructuring assignment to get the value stored in index 0 and name it val and then return only the elements with a val not equal to the event's target value.
In your array, every element is an array (for example: [30, "2021-05-17"]). But you are now checking only the value whether it's present or not.
You have to check [30, "2021-05-17"] whether it's present or not.
Here's an example:
const arr = [[30, "2021-05-17"], [50, "2021-05-17"], [20, "2021-05-17"]];
const valueToDelete = 20;
const newArray = arr.filter(item => item[0] !== valueToDelete);
console.log(newArray);
In your case this would be:
var array = [...this.state.checkboxVal];
const newArray = array.filter(item => item[0] !== parseInt(e.target.value));
console.log(newArray);
this.setState({ checkboxVal: newArray });
Hope this will help you brother. Thank you. :)

Filter array for every 3rd element

I'm having trouble to create an array based on a dataset, I want to filter just some elements of it by choosing one element every 3. Could you help me with this?
This is what I did.
var example = dataset.map(function(d){return d.values
.filter(function(d,i){return (i+1)%3===0;})});
the dataset log: {name:"example1", values: Array(46)}
After applying the new array looks like this. And I'm looking for this [219, 2301, 239.....373]
Thanks
Currently, you're trying to run your filter on every item in the array since you're doing it within an iteration of Array.prototype.map. You should filter the array for every third item first, and then run map on the resulting array to avoid mapping values that will end up being null.
const data = [...]
const dataSet = data
.filter((_, i) => i % 3 === 0)
.map(x => x.value)
You could also do it with a single use of Array.prototype.reduce and doing both filter and map in the same iteration like so:
const data = [...]
const dataSet = data.reduce((acc, curr, i) => {
if (i % 3 === 0) acc.push(curr.value)
return acc
}, [])

Remove item from an array (useState Hook)

Have a useState hook like so:
const [array, updateArray] = useState([])
I know you can add items to the array using a spread operator like so.. (where item is whats being added)
updateArray(array => [...array, item])
how would you remove something from this array? Assuming you have the name of that array item. (remove based off value not index)
Thank you!
If you have a reference to the exact value that was inserted previously (say it's stored in a variable called itemToRemove), you can .filter it out:
updateArray(array.filter(item => item !== itemToRemove));
This works for both primitives and objects, but it's extremely strange to have an exact reference to an object currently in state. For objects, usually what you'll do is you'll need to figure out a way to identify the index of the element in state, probably with findIndex on a unique property, after which you'd set the new state to the array without that index, something like the following:
// say that the array contains objects with a unique 'id' property
// and you need to remove the item with the id of idToRemove
const index = array.findIndex(({ id }) => id === idToRemove);
if (index !== -1) {
updateArray([
...array.slice(0, index),
...array.slice(index + 1)
]);
}

how to get the last 3 elements with specific name value with JMESPATH and javascript?

I have the below json data array:
[{"name":"Button1","date":"1596959802144"},{"name":"Button2","date":"1596959804238"},{"name":"Button3","date":"1596959809334"},{"name":"Button1","date":"1597000878135"},{"name":"Button2","date":"1597000896335"},{"name":"Button3","date":"1597000901536"},{"name":"Button2","date":"1597000904437"},{"name":"Button3","date":"1597000909535"},{"name":"Button1","date":"1597000912250"},{"name":"Button2","date":"1597000939937"},{"name":"Button3","date":"1597000957940"},{"name":"Button2","date":"1597000964640"},{"name":"Button1","date":"1597001005141"},{"name":"Button2","date":"1597001010240"},{"name":"Button3","date":"1597001014845"},{"name":"Button2","date":"1597001021644"},{"name":"Button1","date":"1597001025738"},{"name":"Button2","date":"1597001049030"},{"name":"Button3","date":"1597001054139"},{"name":"Button1","date":"1597001057741"},{"name":"Button2","date":"1597001060340"},{"name":"Button3","date":"1597001062445"},{"name":"Button1","date":"1597002599045"},{"name":"Button1","date":"1597002604128"},{"name":"Button1","date":"1597002609546"},{"name":"Button1","date":"1597002613435"},{"name":"Button1","date":"1597002681736"},{"name":"Button1","date":"1597002690843"},{"name":"Button1","date":"1597002694136"},{"name":"Button1","date":"1597002696349"},{"name":"Button1","date":"1597002699243"}]
and I would like to use JMESPath javascript library to get only the last 3 entries per each distinct name value. For example:
[{"name":"Button3","date":"1597001014845"},{"name":"Button2","date":"1597001021644"},{"name":"Button2","date":"1597001049030"},{"name":"Button3","date":"1597001054139"},{"name":"Button2","date":"1597001060340"},{"name":"Button3","date":"1597001062445"},{"name":"Button1","date":"1597002694136"},{"name":"Button1","date":"1597002696349"},{"name":"Button1","date":"1597002699243"}]
So the last 3 occurrences fro each name = Button*
checking on stackOverflow and I saw that with JQ is possible to do using this function: map_values(delpaths(keys_unsorted[:-2] | map([.])))
Get last N elements for each item of a JSON object
Is there any way to do? or using other javascript module?
If you don't care about the order in your resulting array, here would be a pure JavaScript way to do this:
const getLastNForEveryName = (arr, n) => {
const lastNOfEach = arr.reduce((acc, curr) => {
if(acc[curr.name] == null) { // If the key doesnt exist yet, create it with the current item in the array
acc[curr.name] = [curr];
} else {
if(acc[curr.name].length >= n) // If the array is as big as the desired size alread, remove the first added one
acc[curr.name].shift();
acc[curr.name].push(curr); // push the current item in the array
}
return acc;
}, {})
return Object.values(lastNOfEach).flatMap(l => l); // Just get the values of the object and flatMap it, so that we dont have arrays of arrays
}
// Testing
const values = [{"name":"Button1","date":"1596959802144"},{"name":"Button2","date":"1596959804238"},{"name":"Button3","date":"1596959809334"},{"name":"Button1","date":"1597000878135"},{"name":"Button2","date":"1597000896335"},{"name":"Button3","date":"1597000901536"},{"name":"Button2","date":"1597000904437"},{"name":"Button3","date":"1597000909535"},{"name":"Button1","date":"1597000912250"},{"name":"Button2","date":"1597000939937"},{"name":"Button3","date":"1597000957940"},{"name":"Button2","date":"1597000964640"},{"name":"Button1","date":"1597001005141"},{"name":"Button2","date":"1597001010240"},{"name":"Button3","date":"1597001014845"},{"name":"Button2","date":"1597001021644"},{"name":"Button1","date":"1597001025738"},{"name":"Button2","date":"1597001049030"},{"name":"Button3","date":"1597001054139"},{"name":"Button1","date":"1597001057741"},{"name":"Button2","date":"1597001060340"},{"name":"Button3","date":"1597001062445"},{"name":"Button1","date":"1597002599045"},{"name":"Button1","date":"1597002604128"},{"name":"Button1","date":"1597002609546"},{"name":"Button1","date":"1597002613435"},{"name":"Button1","date":"1597002681736"},{"name":"Button1","date":"1597002690843"},{"name":"Button1","date":"1597002694136"},{"name":"Button1","date":"1597002696349"},{"name":"Button1","date":"1597002699243"}];
console.log(getLastNForEveryName(values, 3));

Filter results to based on specific index

I'm new to ES6 and ReactJS. I need some help to filter out the results in array, in a way, where I can check if the index matches, only then call the function createOptions().
Actual code :
const newArr = items
.filter(this.isEligible(selectedIndex))
.filter((item, index) => this.createOptions(item, index, selectedItem));
Need something like(expected)):
const newArr = items
.filter(this.isEligible(selectedIndex))
.filter((item, selectedIndex) => selectedIndex || selectedIndex+ 2 ? this.createOptions(item, selectedIndex, selectedItem));
Here, I need to filter out the results when the index equals selectedIndex or selectedIndex+2, then call createOptions(item, index, selectedItem);
But, I'm getting some syntax error while trying to do that.
Could you please help me fix that?
If you want to access item at specific index in array, you don't need to filter that array. Just access it by bracket notation:
const itemAtIndex = items[selectedIndex]
const itemAtIndexPlusTwo = items[selectedIndex + 2]

Categories