Home > Back-end >  How to use .filter to find the values between an array and a array in an array
How to use .filter to find the values between an array and a array in an array

Time:07-29

Hello everyone I have two arrays that look like this:

  var arr=  [[1529539200,15.9099,16.15,15.888,16.0773,84805.7,1360522.8],[1529625600,16.0768,17.38,15.865,17.0727,3537945.2,58937516],[1529712000,17.0726,17.25,15.16,15.56,3363347.2,54172164]]

One is an array within an array (as you can see above)

And the other is like this:

var arr2= [ 1647475200, 1647561600, 1647648000, 1647734400, 1647820800, 1647907200, 1647993600, 1648080000, 1648166400, 1648252800]

What I want to do, is use the values from arr2 and see at which values they correspond to the numbers in arr[][0]

For example, arr[100][0] is 153817920. I want javascript to go to arr, and tell me at which point arr2=153817920.

I tried to use .filter but the result just gave out one value, wheras there should be 120 results as arr has a length of 120. Sorry if this is a little confusing, I am not 100% sure what is the correct word for this. I would appreciate any help, thanks!

CodePudding user response:

Is this what you want?

arr = [[1,1], [7,6], [3,9]];
arr2 = [1, 6, 4, 7];
index = arr.map(x => {
    return arr2.findIndex(y => x[0] == y);
})
console.log(index)

CodePudding user response:

As far as I can understand you're trying to find the index of each element from arr in arr2. So please, try this:

const findEachValueOfArrFromArr2 = (arr, arr2) => {
const result = []
for (let i = 0; i < arr.length; i  ) {
    const insideArray = arr[i];
    for (let j = 0; j < insideArray.length; j  ) {
        const element = insideArray[j];
        const arr2Index = arr2.findIndex(e => e === element);
        // if arr[i][j] can not be found in arr2 the result will be -1 
        const resultObj = {
            row: i,
            col: j,
            indexAtArr2: arr2Index,
        }
        result.push(resultObj);
    }
}
return result

}

  • Related