-2

I need to write a function which will clean my array (array 1) :

"yellow pants","black jeans","blue sweater"

From colors, which I keep in array 2.

"yellow","black","blue"

I am iterating over my array 1st and would like a function to clean it from values stacked in array 2

Previously I just defined

function clear(a)
{
  var pattern = /[*,()-.;#&^@?]/g;
  var cleared = a.replace(pattern ,'');  
  return cleared;                                              
}

, where "a" was an element of array 1. But now my "pattern" is multiple string array.

How do I do that using replace() or other function?

I am not comparing 2 arrays at once... I need to compare one element from 1st array with all of the elements from 2nd one. Bet that's not the duplicate of the posted question...

cstr
  • 1
  • 1

2 Answers2

0

The following bit of code will go through each item, checking it against all of the colours. It will then remove the colour from the text and add it to a cleaned item array. It will need a bit more tweaking for functionality if needed. For instance, it currently only adds items that are matched with a colour.

let items = ["yellow pants", "black jeans", "blue sweater"];
let colours = ["yellow", "black", "blue"];
let cleanedItems = [];

Array.prototype.forEach.call(items, (item) => {
  for (var i = colours.length - 1; i >= 0; i--) {
    if (item.includes(colours[i])) {
      cleanedItems.push(item.replace(colours[i], "").trim());
    }
  }
});

console.log(cleanedItems);

Result of console.log(cleanedItems) is as follows;

(3) ["pants", "jeans", "sweater"]
Dan_
  • 1,215
  • 9
  • 18
0

Loop ver yor arrays using either the forEach function or a for-loop vanilla Javascript.

var array1 = ["yellow pants", "black jeans", "blue sweater"];

var array2 = ["yellow", "black", "blue"];

array1.forEach((phrase, idx) => {

  function replace(p) {
    for (let i = 0; i < array2.length; i++) {
      let color = array2[i];
      if (p.indexOf(`${color} `) > -1) {
        return p.replace(color, "").trim();
      }
    }

    return p;
  }

  array1[idx] = replace(array1[idx]);
});

console.log(array1);
Ele
  • 31,191
  • 6
  • 31
  • 67