Home > Back-end >  Get values of array based on binary string
Get values of array based on binary string

Time:07-21

fruits = ["apple", "orange", "banana", "grape"]

dataBinary = "1010";

Since it's a 1 in index 0 and 2 of dataBinary, my fruits should be

myFruits = ["apple", "banana"]

What is the fastest way of doing it (performance wise)? Because I have to run it multiple times with different dataBinary and fruits length is much greater

My attempt

  for (let i = 0; i < dataBinary.length; i  ) {
    const j = parseInt(dataBinary[i]);

    if (j)
      if (data.colors.includes(colors[i])) {
        myFruits.push(id);
        break;
      }
  }

CodePudding user response:

You can make it all in one line with filter:

const fruits = ["apple", "orange", "banana", "grape"]

const dataBinary = "1010";

const myFruits = fruits.filter((fruit, i) => dataBinary[i] === "1");

console.log(myFruits);

You want to only keep fruits that have their respective index in dataBinary equal to 1.

I don't know what's up with the data.colors bit but you could also add that in using the && (AND) operator to only get fruits that match both criteria:

const myFruits = fruits.filter((fruit, i) => dataBinary[i] === "1" && data.colors.includes(colors[i]));

CodePudding user response:

You could also do this assuming fruits and dataBinary have same length

const fruits = ["apple", "orange", "banana", "grape"];
const dataBinary = "1010";

const myFruits = [];
fruits.forEach((fruit, idx) => {
  if (parseInt(dataBinary.charAt(idx))) {
    myFruits.push(fruit);
  }
});

console.log(myFruits);

  • Related