Home > database >  Return Boolean if element of first array is in element of second nested array
Return Boolean if element of first array is in element of second nested array

Time:02-23

I have two different types of arrays firstArrayObject = [{name: "sample", number: 23}, {name: "sample2", number: 25}].

The second object looks like this secondObject = {someAttribute: bla, numbers: [23, 26, 27, 28}

Now i want to check if at least one of the provided number fields of the firstArrayObject is not part of the secondObject's numbers Array. If it is not part, stop the search progress and return true. In the provided example it should return true, because "25" is not part of secondObject.numbers

Im struggling with all the different methods es6 provides like includes, filter, some.

Hopefully anyone can help me out here.

CodePudding user response:

You're on the right track with some:

const result = firstArrayObject.some(
    ({number}) => !secondObject.numbers.includes(number)
);

const firstArrayObject = [{name: "sample", number: 23}, {name: "sample2", number: 25}];
const secondObject = {someAttribute: "bla", numbers: [23, 26, 27, 28]};

const result = firstArrayObject.some(({number}) => !secondObject.numbers.includes(number));

console.log(result);

That says: "Do some (any) of firstArrayObject's elements match the condition 'number is not included in the array `secondObject.numbers'?"

I used destructuring there, but you don't have to:

const result = firstArrayObject.some(
    (element) => !secondObject.numbers.includes(element.number)
);

If secondObject.numbers were a very larger array, you might start out by making a Set of the known numbers, because the has function of a Set is required (by the JavaScript specification) to have better performance than the linear lookup time of includes:

const numbers = new Set(secondObject.numbers);
const result = firstArrayObject.some(
    ({number}) => !numbers.has(number)
);

const firstArrayObject = [{name: "sample", number: 23}, {name: "sample2", number: 25}];
const secondObject = {someAttribute: "bla", numbers: [23, 26, 27, 28]};

const numbers = new Set(secondObject.numbers);
const result = firstArrayObject.some(
    ({number}) => !numbers.has(number)
);

console.log(result);

CodePudding user response:

Hope this helps!! Used forEach and includes function of array. A good resource to learn javascript.

var answer = false;
const firstArrayObject = [{name: "sample", number: 23}, {name: "sample2", number: 25}];

const secondObject = {someAttribute: "bla", numbers: [23, 26, 27, 28]};

function func(obj) {
    if(!secondObject.numbers.includes(obj.number)) answer = true;
}

firstArrayObject.forEach(func);
console.log(answer)

Edit: func can be created as the forEach parameter itself, although the above implementation might make it more readable for beginners.

  • Related