user3109233
user3109233

Reputation:

better way to improve my code without many for loops

I'm trying to optimize my code. I have an array of JSON objects and I need to loop through the objects and see if they contain several words and keep track of the JSON objects if the contain all the worlds, not just one but all of them. I don't want to pass to the function an array of worlds because I feel I will have to add another for loop.Right now, my code goes through every input field and if it's not empty call the function and pass the world in the input field. My code works fine if I just check one word, but I need to check more than one and keep track of the objects that contain all the worlds

My code: workOrdersArray it's a global array.

function searchWO (workOrdersArray) {
            var filteredWO = [];

            for (var i=0; i < workOrdersArray.length; i++) {
                for (var prop in workOrdersArray[i]) {
                    if (myArray[i][prop] == nameKey) {
                            filteredWO.push(workOrdersArray[i]);
                    }
                }

            }
        }

Example: If one input field has the world "Hello" and another input field says "Bye"

var array = [
    { "x":"Bye","y":"Bye","z":"Hello"},
    { "x":"Bye","y":"Bye","z":"Hi"},
    { "x":"Bye","y":"Hello","z":"Hi"},
];

I will store the JSON object inside of the array in an separate array. So the new array will have the obj1 and obj3

Upvotes: 1

Views: 95

Answers (1)

shole
shole

Reputation: 4094

I don't think your array is a valid JavaScript array, but if your array is of the form like

var array = [
    { "x":"Bye","y":"Bye","z":"Hello"},
    { "x":"Bye","y":"Bye","z":"Hi"},
    { "x":"Bye","y":"Hello","z":"Hi"},
];

Then you may try this in ES6+:

var array =  [
  { "x":"Bye","y":"Bye","z":"Hello"},
  { "x":"Bye","y":"Bye","z":"Hi"},
  { "x":"Bye","y":"Hello","z":"Hi"},
];

var keyName = ["Hello", "Bye"];

function searchWO (nameKey, myArray) {
  for(var key of nameKey){
     myArray = myArray.filter(obj => JSON.stringify(obj).indexOf('"' + key + '"') != -1);
  }
  return myArray;
}

// Loop Haters Gonna Hate
function searchWO2 (nameKey, myArray) {
    return nameKey.reduce((ans, key) => ans.filter(obj => JSON.stringify(obj).indexOf('"' + key + '"') != -1) , myArray);
}

console.log(searchWO(keyName, array.slice()));
console.log(searchWO2(keyName, array.slice()));

The .slice() is just a shallow copy as I don't want to modify the source array, you may omit it if you want.

Both function does the same job, choose one you like :)

EDITED:

To ensure the indexOf is searching the value instead of key, one can change to search

'"' + key + '",' and '"' + key + '"}'

Upvotes: 2

Related Questions