3

In my case, the search should go through the first [1] elements of nested arrays. I added a loop through the array elements from the answer, but I can't add the found arrays to the array.

function massivs() {
        let array = [['a', 'mango', 'b','c'], ['d', 'applemango', 'e','f'],['k', 'mangoapple', 's','r']];
        let comp = ['apple', 'mango'];
        let ans = [];
        
        for (let i = 0; i < array.length; i++) {        
            for (el of array[i]) {
                if (comp.every(y => el.includes(y))) {
                    ans.push(el);
                }
            }
        }
        console.log(ans);
}

massivs();
[ 'applemango', 'mangoapple' ]


Expected Result [['d', 'applemango', 'e','f'],['k', 'mangoapple', 's','r']]
Ryan Wilson
  • 10,223
  • 2
  • 21
  • 40
Alex
  • 101
  • 7
  • You just want the arrays that meet your conditions: `array.filter(some_condition)`. Your condition is that one of the elements of the array includes one of your search terms (you have this already). – Wyck Jul 18 '22 at 17:12
  • 1
    If you don't want a complete overhaul of your code, just replace **ans.push(el)** with **ans.push(array[i])** – imvain2 Jul 18 '22 at 17:13

4 Answers4

2

You could do it with just one line of code:

const array = [['a', 'mango', 'b','c'], ['d', 'applemango', 'e','f'],['k', 'mangoapple', 's','r']];
const comp = ['apple', 'mango'];

const result = array.filter(x => comp.every(y => x.some(z => z.includes(y))));

console.log(result);
Guerric P
  • 30,447
  • 6
  • 48
  • 86
1

for of iterates the items of your array, so it's only pushing the element of the array that is included in your search values, push the whole array if found in search and break the loop

 function massivs() {
            let array = [['a', 'mango', 'b','c'], ['d', 'applemango', 'e','f'],['k', 'mangoapple', 's','r']];
            let comp = ['apple', 'mango'];
            let ans = [];
            
            for (let i = 0; i < array.length; i++) {        
                for (el of array[i]) {
                    if (comp.every(y => el.includes(y))) {
                        ans.push(array[i]);
                        break;
                    }
                }
            }
            console.log(ans);
    }

    massivs();
Ryan Wilson
  • 10,223
  • 2
  • 21
  • 40
1

Replace:

ans.push(el)

With:

ans.push(array[i])
NotPitzy
  • 11
  • 1
0

you are pushing the elements of the inner arrays to the answer, hence you only get the elements, if you want the parent array added then you have to push that

for (sub of array) {
    for (el of sub) {
        if (comp.every(y => el.includes(y))) {
            ans.push(sub);
        }
    }
}
MikeT
  • 5,398
  • 3
  • 27
  • 43