BeeNag BeeNag - 6 months ago 8
Javascript Question

Finding an array of data in an array of objects

I have an array of values that looks like this:

["Ashar", 68345, 14, 46100, "Retail", 1, ""]


I also have an array of objects that looks like this:

[
{id: 1, cells: ["Ashar", 68345, 14, 46100, "Retail", 1, ""]},
{id: 2, cells: ["Ashar", 300881, 14, 37000, "Retail", 3, 3]},
{id: 3, cells: ["Rob", 94448, 17, 11395, "Retail", 1, ""]},
{id: 4, cells: ["Shahab", 19023870, 219, 12500, "Retail", 1, ""]},
{id: 5, cells: ["David", 29008000, 229, 12500, "Retail", 5, 26]}
]


What I am trying to do is get the id in the object from the second array by matching the two arrays. I have written a find function which should in theory find the array of values in the second array so that I can access the id. However, it is returning undefined so something is clearly wrong with what I am doing.

Here is the code I currently have:

let row_id = rows.find(row => {
dataEntriesArray === row.cells;
});


where rows is the second array and dataEntriesArray is the first one.

Any help in clearing this up for me would be much appreciated.

Thanks for your time.

Answer

This proposal checks every part of the cells array with the search array and returns the id, if found.

function getId(data, search) {
    var id;
    data.some(a => {
        if (a.cells.every((b, i) => b === search[i])) {
            id = a.id;
            return true;
        }
    });
    return id;
}

var search =["Ashar", 68345, 14, 46100, "Retail", 1, ""],
    data=    [{id: 1, cells: ["Ashar", 68345, 14, 46100, "Retail", 1, ""]}, {id: 2, cells: ["Ashar", 300881, 14, 37000, "Retail", 3, 3]}, {id: 3, cells: ["Rob", 94448, 17, 11395, "Retail", 1, ""]}, {id: 4, cells: ["Shahab", 19023870, 219, 12500, "Retail", 1, ""]}, {id: 5, cells: ["David", 29008000, 229, 12500, "Retail", 5, 26]}];

console.log(getId(data, search));