avatar
remove object from array by property value Javascript

• Handling data using map() and filter() methods:

const instructions = [
  { id: 131 },
  { id: 132 },
  { id: 133 },
];

const instruction_ids = [
  { id: 169, instruction_id: 131 },
];

// Extract the instruction_id values from instruction_ids
const idsToRemove = instruction_ids.map(item => item.instruction_id);

// Use the filter method to remove objects with matching instruction_id values
const updatedInstructions = instructions.filter(item => !idsToRemove.includes(item.id));

console.log(updatedInstructions);

• Handling data using Set() and filter() methods.

const instructions = [
  { id: 131 },
  { id: 132 },
  { id: 133 },
];

const instruction_ids = [
  { id: 169, instruction_id: 131 },
];

// Create a Set of idsToRemove for efficient lookup
const idsToRemoveSet = new Set(instruction_ids.map(item => item.instruction_id));

// Use the filter method with the Set for faster lookups
const updatedInstructions = instructions.filter(item => !idsToRemoveSet.has(item.id));

console.log(updatedInstructions);

• Handling data using Set() and reduce() methods.

const instructions = [
  { id: 131 },
  { id: 132 },
  { id: 133 },
];

const instruction_ids = [
  { id: 169, instruction_id: 131 },
];

// Create an object for efficient lookup
const idsToRemoveMap = instruction_ids.reduce((map, item) => {
  map[item.instruction_id] = true;
  return map;
}, {});

// Use the filter method to remove objects with matching instruction_id values
const updatedInstructions = instructions.filter(item => !idsToRemoveMap[item.id]);

console.log(updatedInstructions);

• Use for-loop to handle:

const instructions = [
  { id: 131 },
  { id: 132 },
  { id: 133 },
];

const instruction_ids = [
  { id: 169, instruction_id: 131 },
];

const updatedInstructions = [];

for (const instruction of instructions) {
  let shouldInclude = true;
  for (const idItem of instruction_ids) {
    if (instruction.id === idItem.instruction_id) {
      shouldInclude = false;
      break;
    }
  }
  if (shouldInclude) {
    updatedInstructions.push(instruction);
  }
}

console.log(updatedInstructions);
24
remove invalid elements from array in PHP remove an object from array remove last character from String remove underline for anchors tag
You need to login to do this manipulation!