Home > OS >  How do I remove elements from a set of arrays with elements that are concatenated to a string in Jav
How do I remove elements from a set of arrays with elements that are concatenated to a string in Jav

Time:04-27

I currently have this set:

Set1 = {
Alpha: [One, Two], 
Beta: [One, Two, Three], 
Delta: [One]
}

I also have this array of elements:

Arr1 = [Alpha_One, Beta_One, Beta_Two, Delta_One]

I'm looking for a way to programmatically remove all of the elements that are found in this set to it's respective array, like so:

Set1 = {Alpha: [Two], Beta: [Three], Delta: []}

As far as I know, the forEach() method does not take if statements, so I don't know if there is another method to do it.

CodePudding user response:

Just find the index and splice.

let Set1 = {
"Alpha": ["One", "Two"], 
"Beta": ["One", "Two", "Three"], 
"Delta": ["One"]
};

let Arr1 = ["Alpha_One", "Beta_One", "Beta_Two", "Delta_One"];
Arr1.forEach(e=>{
let t = e.split('_');
if(Set1.hasOwnProperty(t[0])){
  var index = Set1[t[0]].indexOf(t[1]);
  if (index !== -1) {
    Set1[t[0]].splice(index, 1);
  }
}
});
console.log(Set1);

CodePudding user response:

Split your Arr1 and splice elem from exact key

const Arr1 = ['Alpha_One', 'Beta_One', 'Beta_Two', 'Delta_One'];

const Set1 = {
    Alpha: ['One', 'Two'], 
    Beta: ['One', 'Two', 'Three'], 
    Delta: ['One']
};
const newArr = [];
Arr1.forEach(itemArr => {
    newArr.push(itemArr.split('_'));
})

for (let key in Set1) {
    newArr.forEach(itemArr => {
        if (key === itemArr[0]) {
            Set1[key].forEach((item, i) => {
                if (item === itemArr[1]) {
                    Set1[key].splice(i, 1)
                }

            });
        }
    })
};

console.log(Set1)

  • Related