Home > other >  Jquery, Find a subarray that contains a value
Jquery, Find a subarray that contains a value

Time:11-24

I would like to "push" a variable into a subarray which contains a value. This is to integrate into a "for loop". But it does not work ..:-( where is my mistake ? Thanks.

var add = "purple";
var val = "white";

arr = [
    ["blue","green","brown"],
    ["white","gray","black"],
    ["yellow","pink","red"]
];

subarr = [].indexOf(val) > -1;
arr[subarr].push(add);

/*
expected output :
arr = [
    ["blue","green","brown"],
    ["white","gray","black","purple"],
    ["yellow","pink","red"]
]
*/

CodePudding user response:

You are looking

subarr = [].indexOf(val) > -1;

into an empty array.

Instead, you could find the sub array and if exists push the value to it.

const
    add = "purple";
    val = "white",
    arr = [["blue", "green", "brown"], ["white", "gray", "black"], ["yellow", "pink", "red"]],
    sub = arr.find(a => a.includes(val));

if (sub) sub.push(add);

console.log(arr);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related