Remove array from json array wrt if condition in React JSX - javascript

How to remove an array from json array in react js. I tried something like this. but not working
Now the response is directly set to atate as follows
let { newData} = response;
please help to filter item. Either from response or from state variable
response.map((res, index) => {
if (res.status==1) {
res.splice(index, 1) // remove element
};
})
response is [object Object] when i alerted
[
{id:1, status:1},
{id:2, status:0},
{id:3, status:1},
]

Use filter instead of map and filter out the unwanted object/s.
const filteredArray = response.filter((res) => res.status !== 1);
Please just be aware that this will create a new array and not mutate your original array.

You should create a new one of Array, You can try..
let temp = []
response.forEach((res, index) => {
if (res.status !== 1) {
temp.push(res)
}
})

The better solution is to use the filter method, or if you still want to use the splice, It should be response.splice
Note: Using the splice approach is wrong as pointed out by #VLAZ, as it shifts the elements but the indexing by forEach will continue irrespective of the elements spliced off.
var response = [
{id:1, status:1},
{id:2, status:0},
{id:3, status:1},
]
response.forEach((res, index) => {
if (res.status==1) {
response.splice(index, 1) // remove element
};
})
console.log(response);

Related

Filter deep nested array

I'm having some issues with filtering 2 arrays of objects. My goal is to filter the main array with another array, both arrays of numbers.
Demo code below
partners?.map((e) => {
let products = e.products.map(a => a.externalProductId)
let porArr: number[] = active.map((a) => a.externalProductId);
if (products.filter(item => porArr.includes(item))) {
return console.log(e)
} else {
return console.log('bad')
}
})
products preview
[
6268,
6267,
9745,
9746
]
porArr preview
[
6267,
6270,
6269,
6641,
9559,
9560,
9660,
9663,
9665
]
for some reason the func still returns always true in the if rule.
Any help greatly welcome!
Since you're not assigning the filtered array anywhere, you don't need to use .filter(). Use .some() to test if any of the array elements satisfy the condition.
if (products.any(product => porArr.includes(product)) {
// do something
}

JavaScript why is map not returning all the indexes?

I dont know but this seems like a bug with javascript or it has to be my machine or something this map is not returning all indexes
const words = [];
let array = [
{
id:"h2j3x33",
author:"Zindril",
body:"Glad to help. Hope it helps you clear even faster next reset!",
permalink:"zindi.page",
utc:1624278978,
replies:""
},
{
id:"33",
author:"highperson",
body:"Im a the best!",
permalink:"thebest.com",
utc: 054,
replies: ""
},
{
id:"43",
author:"charizard",
body:"fire burn",
permalink:"dragon.com",
utc:342342,
replies: {id: 324, author: "Ash", body: "Skinny", permalink: "pokemon.com", utc: 1, replies: ""}
}
]
words.push(array)
console.log(words)
console.log(words.length) // this says the length is 1 so the index will be 0
let whyOnlyFor1Obj = words.map((word, idx, arr) => word[idx]) // word[idx] only returns the first object if I try forEach i get undefined
console.log(whyOnlyFor1Obj)
The funny thing is when I do
let whyOnlyFor1Obj = words.map((word, idx, arr) => word[2]) // or word[1] I get the other Objects
console.log(whyOnlyFor1Obj)
Is it me or what is wrong with JS on this?
If you use forEach you get undefined because you are defining function for each element of the array and since you have an array inside another array, you need to use forEach inside forEach just like this.
words.forEach(function(val,idx){
val.forEach((value,index)=>{
console.log(value.id);
})

Filter a JavaScript array for elements greater zero

I’ve got a "2D"-JavaScript array, holding these kind of data:
let arr = [
["w",0],
["x",1],
["y",0],
["z",2]
]
I would like to remove all rows that contain a 0 for their second item, so that the resulting array would look like this:
arr = [
["x",1],
["z",2]
]
Any elegant thoughts?
Use Array.filter() where you can check the inner array do not contain element value 0 on second position by item[1] !== 0:
let arr = [
["w",0],
["x",1],
["y",0],
["z",2]
];
var res = arr.filter(item => item[1] !== 0);
console.log(res);
Using filter() you can loop through each element of the array and pass that element in a callback function which then return the same/modified element based on the condition. So, item is the element of the array and this is passed to a callback function. Since, we have only one line code in callback we can replace that callback function with item[1] !== 0 and it also return by default when the condition is satisfied.
A solution with Array.prorotype.filter and array destructuring assignment:
let arr = [
["w",0],
["x",1],
["y",0],
["z",2]
]
const filtered = arr.filter(([_,a]) => a > 0);
console.log(filtered);

Remove values using condition from multidimensional array using java-script

I have a multidimensional array as following.
[['Base: Values','55','98','90.8'],['Value First','55','98','90.8'],['Top','55','98','90.8'],['Bottom','55','98','90.8']]
I want to remove entire values if it includes 'Top' or 'Bottom', so that i will get a result like this:
[['Base: Values','55','98','90.8'],['Value First','55','98','90.8']]
Somebody give me a solution please. Thanks in advance.
You can filter the array, providing a function to determine if an element should be included or not :
array.filter(e => !e.includes('Top') && !e.includes('Bottom'));
Example:
const data = [
['Base: Values','55','98','90.8'],
['Value First','55','98','90.8'],
['Top','55','98','90.8'],
['Bottom','55','98','90.8']
]
const filtered = data.filter(e => !e.includes('Top') && !e.includes('Bottom'));
console.log(filtered)
console.log(data)
EDIT: To exclude if any string in array values contains a specific part, you could change the predicate to check if at least one string contains the part:
array.filter(e => !e.some(i => i.includes('part to find')));
Example:
const data = [
['Base: Values','55','98','90.8'],
['Value First','55','98','90.8'],
['Top','55','98','90.8'],
['Bottom','55','98','90.8']
]
const filtered = data.filter(e => !e.some(i => i.includes('Value')));
console.log(filtered)
console.log(data)

How to find many results from an array with Lodash?

The following code loops thorugh an Object array, uses _.find to find the object of a certain category and push it into the panoramaCats array:
this.panoramas.forEach(panorama => {
const panoramaCat = _.find(this.panoramas, { category: panorama.category })
const panoramaCats = []
panoramaCats.push(panoramaCat)
payload[panorama.category] = panoramaCats
})
I thought _.find would find ALL the objects with that category, but it only finds the first one.
How to change the code so _.find finds ALL the object with that category?
Use ._matches to find objects matching your criteria.
this.panoramas.forEach(panorama => {
const panoramaCats = _.find(this.panoramas, _.matches({ category: panorama.category }))
payload[panorama.category] = panoramaCats
})
this.panoramas.forEach(panorama => {
payload[panorama.category] = _.find(this.panoramas, {category: panorama.category})
})
Have you considered using _.groupBy? I think it's simpler than manually looping through your collection.
payload = _.groupBy(this.panoramas, 'category')
If you need to preserve other pre-existing properties in your payload object you could use _.merge:
payload = _.merge(payload, _.groupBy(this.panoramas, 'category'))

Categories