Critical Developers

Programmers Knowledge Base

Find and replace items in an array in javascript

Today, will explain you how to find elements in array and replace it or manipulate it. I have created two methods for finding array element or item in simple array or nested array, it will work for both. The method can find array inside array and we can replace it.

1) First method is used to compare 2 arrays, it will check whether both the array are same or not.


function Compare2Arrays(arr1, arr2) {
    return Array.isArray(arr1) && Array.isArray(arr2) && arr1.length === arr2.length && arr1.every((val, index) => val === arr2[index]);
}

2) Second function is used to find array inside main Array and if match found then we can easily set/ replace it.

 
function FindArrInsideArr(mainArr, searchArr) {
    var matchedArr = [];
    if (Compare2Arrays(mainArr, searchArr)) {   // if mainArr is not nested Array
        matchedArr.push(mainArr);    // array found
        alert(JSON.stringify(matchedArr));
        // here we can manipulate mainArr...
    }
    else {
        for (var i in mainArr) {
            if (!mainArr.hasOwnProperty(i)) continue;
            if (typeof mainArr[i] == 'object') {
                if (mainArr[i] != null) {
                    if (Compare2Arrays(mainArr[i], searchArr)) {
                        matchedArr.push(mainArr[i]);    // array found in nested array
                        alert(JSON.stringify(matchedArr));
                        // here we can manipulate mainArr[i]...
                    }
                    else {
                        matchedArr = matchedArr.concat(FindArrInNestedArr(mainArr[i], searchArr));
                    }
                }
            }
        }
    }
    return mainArr;
}
Thats it !!!
Comments are closed