Create new array with deleted values (React Native) - javascript

I have an array like this one :
[
Object {
"hex": "#00b2b9",
"label": "text",
"value": "364",
},
Object {
"hex": "#50690e",
"label": "text",
"value": "354",
},
Object {
"hex": "#925fa3",
"label": "text",
"value": "355"
}]
I have another array with this :
Array [
"355",
"356"
]
I'm looking to create a the first array but without the objects containing value 355 and 356. I tried with .filter()... but I'm a newbie with JS & React Native :-)
I tried some stuffs but almost every time I recreate my Array only with the values (i'm losing the objects inside)...
What I want to do is :
If I found 355 and 356 in my First Array, I delete the objects with them and I recreate my array with the only object remaining (value 364)
I was thinking about sth like that :
myFirstArray.filter(item => item.value != mySecondArray.value) but it's not a success ...
Thanks for help

The previous answers involve iterating over your id's array many times.
A more performant solution would be to store the id's in a set and then use that combined with a filter to produce your new array.
const arr = [
{
"hex": "#00b2b9",
"label": "text",
"value": "364",
},
...,
{
"hex": "#925fa3",
"label": "text",
"value": "355"
}];
const ids = ["354", "355"];
const idSet = new Set(ids);
const output = arr.filter(e => !idSet.has(e.value));

var firstArray = [{
"hex": "#00b2b9",
"label": "text",
"value": "364",
},
{
"hex": "#50690e",
"label": "text",
"value": "354",
},
{
"hex": "#925fa3",
"label": "text",
"value": "355"
}]
var secondArray = [
"355",
"356"
]
var thirdArray = firstArray.filter(item => secondArray.includes(item.value))
console.log(thirdArray)

You are nearly there, just use Array#includes() to determine whether or not the value of an item is in the second array:
myFirstArray.filter(item => !mySecondArray.includes(item.value))
let myFirstArray = [{
"hex": "#00b2b9",
"label": "text",
"value": "364",
},
{
"hex": "#50690e",
"label": "text",
"value": "354",
},
{
"hex": "#925fa3",
"label": "text",
"value": "355"
}
]
let mySecondArray = [
"355",
"356"
]
console.log(
myFirstArray.filter(item => !mySecondArray.includes(item.value))
)

Related

How to update deeply nested array of objects JavaScript

I have the following Array of object using this information I want to update array of object with value:a without mutating it directly (I am able to solve it using index but I don't want to update it using index) below is the code that I have tried so far
ccategory.map((item) =>
item.id === payload.id
? {
...item,
categoryItems: item.categoryItems.map(
(catItem) => catItem.categoryItemID === payload.categoryItemID
// stuck here how should I update categorySubItems?
),
}
: item
),
const payload={
"id": "4476c379-2c4f-4454-b59e-cae2f62fdfe2",
"categorySubItemsID": "c2cba4d6-5635-4b5c-acf3-b93b4d435aa9",
"categoryItemID": "fdb0e86b-a2d9-4029-8988-9f50121794d3",
"value": "a"
}
MyJSON looks like this
const category=[
{
"id": "4476c379-2c4f-4454-b59e-cae2f62fdfe2",
"categoryName": "Car",
"categoryFields": [
{
"name": "Car Name",
"type": "text",
"categoryID": "e9da78fb-d349-4b03-9b77-e3cc0dc57d25"
},
{
"name": "Price",
"type": "number",
"categoryID": "c9e147a6-b5d1-424b-99bf-a973ce189322"
}
],
"categoryItems": [
{
"categoryItemID": "fdb0e86b-a2d9-4029-8988-9f50121794d3",
"categorySubItems": [
{
"categorySubItemsID": "c2cba4d6-5635-4b5c-acf3-b93b4d435aa9",
"value": "",
"label": "Car Name",
"type": "text",
"categoryLinkID": "e9da78fb-d349-4b03-9b77-e3cc0dc57d25"
},
{
"categorySubItemsID": "01d5e1e7-3927-42a6-ad05-7399a5895096",
"value": "",
"label": "Price",
"type": "number",
"categoryLinkID": "c9e147a6-b5d1-424b-99bf-a973ce189322"
}
]
},
{
"categoryItemID": "f13237d7-abfd-40d3-ae35-0b59ddf5734e",
"categorySubItems": [
{
"categorySubItemsID": "2af389b9-03bc-41d3-86bb-8bf324ca3cb3",
"value": "",
"label": "Car Name",
"type": "text",
"categoryLinkID": "e9da78fb-d349-4b03-9b77-e3cc0dc57d25"
},
{
"categorySubItemsID": "934ef505-72bb-4d64-adf1-2aa5e928a539",
"value": "",
"label": "Price",
"type": "number",
"categoryLinkID": "c9e147a6-b5d1-424b-99bf-a973ce189322"
}
]
}
]
},
{
"id": "9882b210-2d99-43a3-8aea-9f7d7c88eeda",
"categoryName": "Bike",
"categoryFields": [
{
"name": "Bike Name",
"type": "text",
"categoryID": "73bee24c-ef64-4798-bc37-5fe90cbc8de7"
}
],
"categoryItems": []
}
]
In your inner .map(), if catItem.categoryItemID === payload.categoryItemID matches, you can return a new object that has an updated categorySubItems, which you can update by creating a new array by mapping catItem.categorySubItems. When mapping the sub category items, if your categorySubItemsID matches the one from the payload object, you can return a new updated object with a new value set to that of payload.value, otherwise, you can keep the original item, eg:
ccategory.map((item) =>
item.id === payload.id
? {
...item,
categoryItems: item.categoryItems.map((catItem) =>
catItem.categoryItemID === payload.categoryItemID
? {
...catItem,
categorySubItems: catItem.categorySubItems.map(subCatItem =>
subCatItem.categorySubItemsID === payload.categorySubItemsID
? {...subCatItem, value: payload.value}
: subCatItem
)
}
: catItem
),
}
: item
),
As you can see, this can get quite unwieldy. That's why it's often useful to use something like useImmer(), which allows you to directly modify a "draft" state value in an immutable way while keeping your state updates mutable.

Change Object Value using forEach

I am trying to change the value of object from the array but, it's not work as expected. I tried following.
const arrObj = [
{
"label": "test1",
"value": 123,
"type": "number",
"field": {
"label": "another",
"description": "abcd"
}
},
{
"label": "test2",
"value": 111,
"type": "number"
},
]
arrObj.forEach(obj => {
obj = {...obj, ...obj.field}
delete obj.field
})
console.log("after:", arrObj);
Also I found some solution that to use index but, it add index before the object.
const arrObj = [
{
"label": "test1",
"value": 123,
"type": "number",
"field": {
"label": "abcd",
"description": "abcd"
}
},
{
"label": "test2",
"value": 111,
"type": "number"
}
]
arrObj.forEach((obj, index) => {
obj[index] = {...obj, ...obj.field}
delete obj.field
})
console.log("after:", arrObj);
How can I do with forEach?
Edit:
I want to remove the field object and assign/overwrite all the property outside.
Using map and assigning the result is probably a better way of doing this, but if you want to use forEach, you need to assign to the original array inside the loop:
const arrObj = [
{
"label": "test1",
"value": 123,
"type": "number",
"field": {
"label": "another",
"description": "abcd"
}
},
{
"label": "test2",
"value": 111,
"type": "number"
},
]
arrObj.forEach(({ field, ...rest}, idx, orig) => {
orig[idx] = { ...rest, ...field }
})
console.log(arrObj);
I would use map to change an array, but you may have a reason that you wish to modify the original. You could just reassign arrObj to the output of the map.
const arrObj = [
{
"label": "test1",
"value": 123,
"type": "number",
"field": {
"label": "another",
"description": "abcd"
}
},
{
"label": "test2",
"value": 111,
"type": "number"
},
]
const newArr = arrObj.map(( obj ) => {
const {field, ...rest} = obj
return {...field, ...rest}
})
console.log("after:", newArr);

get values in an array inside an array

I have a question here I want to get all the value of the values array inside this array.
const sample = [
{
"key": "sampleKey", "values":
[
{ "key": "insidesampleKey", "value": 2 },
{ "key": "insideofinside", "value": 2 }
]
},
{
"key": "sampleKey2", "values":
[
{ "key": "insideSampleKey2", "value": 1 }
]
},
{
"key": "samplkey3", "values":
[
{ "key": "insideofsampleKey3", "value": 1 }
]
}
]
So far, I can only print the first one console.log(sample[0].values[0].value). I appreciate with any helps. Thanks much and have a great weekend
I think flatMap may be the best way to deal with this.
sample.flatMap(outer => outer.values.map(inner => inner.value))
You can use reduce and concat to get a flat, single array.
const sample = [{"key":"sampleKey","values":
[{"key":"insidesampleKey","value":2},{"key":"insideofinside","value":2}]},
{"key":"sampleKey2","values":[{"key":"insideSampleKey2","value":1}]},
{"key":"samplkey3","values":[{"key":"insideofsampleKey3","value":1}]}]
var values = sample.reduce((acc, item) => acc.concat(item.values.map(v=> v.value)),[]);
console.log(values);
The easiest method is to use a flatMap over the array as below. You can use polyfill for browsers that don't support the same yet. Use MDN to learn more.
sample.flatMap(item => item.values.map(inner => inner.value))
If you want to print the other value properties, just map over the array, then look at the values array, then look at value, and finally use flat to get a single array:
const sample = [{
"key": "sampleKey",
"values": [{
"key": "insidesampleKey",
"value": 2
}, {
"key": "insideofinside",
"value": 2
}]
},
{
"key": "sampleKey2",
"values": [{
"key": "insideSampleKey2",
"value": 1
}]
},
{
"key": "samplkey3",
"values": [{
"key": "insideofsampleKey3",
"value": 1
}]
}
];
console.log(sample.map(e => e.values.map(x => x.value)).flat(1));

Add columns value in react.js

What is the best approach to add all the columns value?
json
[
{
"id": "men",
"label": "men",
"value": 3,
"color": "#468df3"
},
{
"id": "women",
"label": "women",
"value": 5,
"color": "#ba72ff"
},
{
"id": "children",
"label": "children",
"value": 5,
"color": "#a1cfff"
}
]
I am fetching data from the server I like to add all the values and display it in the console.
For example const value = 3+5+5 = 13 in console.
That's not related to reactjs, simply
let raw = '[{"id": "men","label": "men","value": 3,"color": "#468df3"},{"id": "women","label": "women","value": 5,"color": "#ba72ff"},{"id": "children","label": "children","value": 5,"color": "#a1cfff"}]';
let data = JSON.parse(raw);
let sum_value = data.reduce((sum, current)=>{
return sum + current.value
}, 0);
console.log(sum_value);

Comparing arrays of objects and remove duplicate [duplicate]

This question already has answers here:
Remove duplicates in an object array Javascript
(10 answers)
Closed 5 years ago.
I have an array containing arrays of objects which I need to compare.
I've looked through multiple similar threads, but I couldn't find a proper one that compares multiple arrays of objects (most are comparing two arrays of objects or just comparing the objects within a single array)
This is the data (below is a JSFiddle with code sample)
const data = [
[
{
"id": "65",
"name": "Some object name",
"value": 90
},
{
"id": "89",
"name": "Second Item",
"value": 20
}
],
[
{
"id": "89",
"name": "Second Item",
"value": 20
},
{
"id": "65",
"name": "Some object name",
"value": 90
}
],
[
{
"id": "14",
"name": "Third one",
"value": 10
}
]
]
I want to remove all duplicate arrays of objects, regardless of the length of data (there could be a lot more records).
I managed to get the unique ones extracted into an object:
const unique = data.reduce(function(result, obj) {
return Object.assign(result, obj)
}, [])
That doesn't work for me though, because I need 1 of the duplicated arrays to remain and the returned data to be an array as well, instead of an object. E.g.:
// result I need
[
[
{
"id":"65",
"name":"Some object name",
"value":90
},
{
"id":"89",
"name":"Second Item",
"value":20
}
],
[
{
"id":"14",
"name":"Third one",
"value":10
}
]
]
So how do I compare each array of objects to the others in the parent array and preserve one of each duplicated or unique array of objects?
JSFiddle
you can achieve so by using function.As below. Not sure about best optimum way of doing so.
var testArray = [
[
{
"id": "65",
"name": "Some object name",
"value": 90
},
{
"id": "89",
"name": "Second Item",
"value": 20
}
],
[
{
"id": "89",
"name": "Second Item",
"value": 20
},
{
"id": "65",
"name": "Some object name",
"value": 90
}
],
[
{
"id": "14",
"name": "Third one",
"value": 10
}
]
]
function removeDuplicatesFromArray(arr){
var obj={};
var uniqueArr=[];
for(var i=0;i<arr.length;i++){
if(!obj.hasOwnProperty(arr[i])){
obj[arr[i]] = arr[i];
uniqueArr.push(arr[i]);
}
}
return uniqueArr;
}
var newArr = removeDuplicatesFromArray(testArray);
console.log(newArr);
const data = [
[
{
"id": "65",
"name": "Some object name",
"value": 90
},
{
"id": "89",
"name": "Second Item",
"value": 20
}
],
[
{
"id": "89",
"name": "Second Item",
"value": 20
},
{
"id": "65",
"name": "Some object name",
"value": 90
}
],
[
{
"id": "14",
"name": "Third one",
"value": 10
}
]
];
const temp = {};
const result = [];
data.forEach(itemArr => {
const items = itemArr.filter(item => {
const isUnique = temp[`${item.id}-${item.name}-${item.value}`] === undefined;
temp[`${item.id}-${item.name}-${item.value}`] = true;
return isUnique;
});
if (items.length !== 0)
result.push(items);
});
console.log(result);

Categories

Resources