1

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

1
  • have you try lodash? Commented Sep 4, 2018 at 10:48

3 Answers 3

2

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));
Sign up to request clarification or add additional context in comments.

Comments

1
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)

1 Comment

thank you Lazar! It's working. You all came with the same idea. So cool
1

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))
)

1 Comment

Thank you Luca ! It' working. I was so close but it's better to understand the concept now !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.