1

I want to separate color, size, material etc where a and b array always same length.

a = ["Color", "Color", "color", "color", "Size", "size"]

b = ["black", "red", "blue", "green", "small", "large"]

i want

output = [['black','red','blue','green'], ['small','large'],...]
4
  • and what did you try? Commented Jun 20, 2020 at 13:52
  • Will a and b always be the same length? Commented Jun 20, 2020 at 13:52
  • Doesn't the output { color: ['black', 'red', 'blue', 'green'], size: ['small', 'large'] } make more sense? Commented Jun 20, 2020 at 13:54
  • yes a and b always same length Commented Jun 20, 2020 at 13:55

3 Answers 3

3

You can make use of reduce and then take values by Object.values():

var a = ["Color", "Color", "color", "color", "Size", "size"];
var b = ["black", "red", "blue", "green", "small", "large"];

var result = Object.values(b.reduce((acc, elem,i)=>{
  const key = a[i].toLowerCase();
  acc[key] = [...(acc[key] || []), elem];
  return acc;
},{}));

console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

1

Here you can find my answer to your question. It stores in a dictionary first, then converts it to an array.

The below code will also generate the desired result for the cases where Color and Size randomly ordered.

const a = ["Color", "Color", "color", "color", "Size", "size", "color"];
const b = ["black", "red", "blue", "green", "small", "large", "white"];

let dict = [];
for(let i=0; i<a.length; i++) {
    let lowerCase = a[i].toLowerCase();
    if(!dict[lowerCase]) {
       dict[lowerCase] = [];
    }
    dict[lowerCase].push(b[i]);
}

let arr = [];
for(let item in dict) {
    arr.push(dict[item]);
}

console.log(arr);

Comments

0

To merge both arrays you can also use forEach:

const a = ["Color", "Color", "color", "color", "Size", "size"];

const b = ["black", "red", "blue", "green", "small", "large"]; const newArray = []

const newArray2 = a.forEach((color) => {newArray.push(a+b);console.log(newArray)});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.