Useful Tips in JS part 2
Sorting arrays randomly
array.sort((a, b) => 0.5 - Math.random());
Sorting data from a to z
datas.sort((data, b) => data.name.localeCompare(b.name));
Sorting data from z to a
datas.sort((data, b) => data.name.localeCompare(b.name)).reverse()
We can delete data from an array using filter method then we can pass it to the react state like
const movies = this.state.movies.filter((m) => m._id !== movie._id);
Clone an object and modify the given indexed Value using JavaScript
handleIncrement = (counter) => {
const counters = [...this.state.counters]; // Clone Object
const index = counters.indexOf(counter); // Find The Index
counters[index] = { ...counter }; // Modify given (counter) with given index
counters[index].value++; // Increment Value or whatever
this.setState({ counters }); // setState the new object (Cloned Object)
};
Get total selected (counted) items in React. uses for Count shop items. Will return total items in basket
this.state.counters.filter((c) => c.value > 0).length
Create array with given length. This will return an array with given length.
const createArrays = length => [...Array(length)]
Also we can manipulate data in it like
creatArrays(5).map((m , index) => "Given Value" + index)