0

Currently I have an array with values:

var array1 = ['new_user', 'promotion']

What i need to do is filter and an object with this array1:

OBJc = [
    {"id": 1, "array_": ['promotion', 'test1']},
    {"id": 2, "array_": ['test444', 'test1']},
    {"id": 3, "array_": ['new_user', 'test1']}
]

I need to filter this json based of if "array_" has any of the values in array1.

So the output would be:

[
    {"id": 1, "array_": ['promotion', 'test1']},
    {"id": 3, "array_": ['new_user', 'test1']}
]
2
  • What have you tried to solve this problem so far? What error did you get? Commented Jun 4, 2021 at 18:27
  • Use a fiddle with your code Commented Jun 4, 2021 at 18:31

4 Answers 4

1
const filtered = OBJc.filter(obj => obj.array_.some(array1.includes))

Or with es6 destructuring:

const filtered = OBJc.filter({ array_ } => array_.some(array1.includes))

Basically you check each array_ element to see if it's included in array 1, and keep only those who satisfy this condition.

Sign up to request clarification or add additional context in comments.

Comments

1

You want to filter, so lets filter.

OBJc.filter()

Now, you want to return true when your property has some value right?

OBJc.filter(value => {
  return value['array_'].includes(x)
})

But there are multiple ones, and you need to know if at least some those values are on your list

OBJc.filter(value => {
  return array1.some(arrV => value['array_'].includes(arrV));
})

Or if you like one liners:

OBJc.filter(value => array1.some(arrV => value['array_'].includes(arrV)));

Comments

0

Here's the solution:

var array1 = ['new_user', 'promotion']

JSONstr = [
    {"id": 1, "array_": ['promotion', 'test1']},
    {"id": 2, "array_": ['test444', 'test1']},
    {"id": 3, "array_": ['new_user', 'test1']}
]

const result = JSONstr.filter(obj => {
    let found = false;
    array1.forEach(elm => {
        if (obj.array_.includes(elm)) {
            found = true;
        }
    });
    if (found) {
        return true;
    }
});

console.log(result);

Comments

0

Here's one way if you like playing with booleans.

const reduceTruth = (a, b) => a || b;

const matches = JSONstr.filter(element => {
    return element.array_.map( x => array1.map(y => y == x).reduce(reduceTruth, false)).reduce(reduceTruth, false);
});

Comments

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.