0

I am trying to create a form for uploading products with variants.

I am joining each value from originalArray into a unique value in a newArray. Example of joined values into one unique value: red/small/modern

However, I want check if there is already a unique (joined) value in the newArray. If true, keep exiting value and price in the newArray.

So if, value "red/small/modern" already exist with price 888, an array item of price of null should not be returned into the newArray.

let originalArray = [
  [
    { value: 'red', id: 99, price: null },
    { value: 'blue', id: 100, price: null },
  ],
  [
    { value: 'small', id: 101, price: null },
    { value: 'medium', id: 102, price: null },
  ],
  [
    { value: 'modern', id: 103, price: null },
    { value: 'classic', id: 104, price: null },
  ],
];
//
// existing array item
let newArray = [
  { value: 'red/small/modern', id: 1, price: 888 },
  { value: 'blue/medium/modern', id: 2, price: 100 },
];
//
console.log('example 1:', newArray); // [{…}, {…}]
//

newArray = originalArray
  .map((elem) => {
    return elem.map(({ value }) => value);
  })
  .reduce((acc, cur) => {
    return acc.flatMap((seq) => {
      return cur.map((part) => `${seq}/${part}`);
    });
  })
  .map((elem) => {
    return { value: elem, price: null };
  });
//
//
// price for value "red/small/modern" and "blue/medium/modern" should not be null, as they are already set in the newArray
console.log('example 2:', newArray);

Hope question make sense.

1 Answer 1

2

You can filter the elements which are not already in the newArray, and push the new ones into it:

let originalArray=[[{value:"red",id:99,price:null},{value:"blue",id:100,price:null}],[{value:"small",id:101,price:null},{value:"medium",id:102,price:null}],[{value:"modern",id:103,price:null},{value:"classic",id:104,price:null}]];
let newArray=[{value:"red/small/modern",id:1,price:888},{value:"blue/medium/modern",id:2,price:100}];

const allCombinations = originalArray
  .map((elem) => {
    return elem.map(({ value }) => value);
  })
  .reduce((acc, cur) => {
    return acc.flatMap((seq) => {
      return cur.map((part) => `${seq}/${part}`);
    });
  })
  .map((elem) => ({ value: elem, price: null }));

newArray.push(
  ...allCombinations.filter(({ value }) => {
    return newArray.every(existing => existing.value !== value);
  })
);

console.log('example 2:', newArray);
.as-console-wrapper { max-height: 100%!important; }

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

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.