1

The first array is something like this

arrayA = [{x:"abc",y:2},{x:"cde",y:3},{x:"xyz",y:2}]

The second array is

arrayB = ["abc","cde","efg","ghi","xyz"]

I want to insert the element of arrayB as key-value pair which is missing in arrayA as key is the element from arrayB and value will be 0 I want the resultant arrayResult something like this

arrayResult = [{x:"abc",y:2},{x:"cde",y:3},{x:"efg",y:0},{x:"ghi",y:0},{x:"xyz",y:2}]


I tried this but didn't get the required result

for (let i = 0; i < arrayB.length; i++) {
 for (let j = 0; j <arrayA.length; j++) {
  if(arrayB[i] !== arrayA[j].x) {
   arrayA.push({x:arrayB[i],y:0})
   }
 }
}

I am new to js. can anyone help me with this?

3 Answers 3

1

You could take a closure over an index of arrayA and check the value of arrayB is equal of the first array, then return that object, otherwise create a new object and return this by iterating the second array.

const
    arrayA = [{ x: "abc", y: 2 }, { x: "cde", y: 3 }, { x: "xyz", y: 2 }],
    arrayB = ["abc", "cde", "efg", "ghi", "xyz"],
    result = arrayB.map((i => x => arrayA[i].x === x
        ? arrayA[i++]
        : { x, y: 0 }
    )(0));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Comments

0

You can use Array.reduce for this job:

let arrayA = [{x:'abc', y:2}, {x:'cde', y: 3}, {x:'xyz', y:2}]
let arrayB = ['abc', 'cde', 'efg', 'ghi', 'xyz']

Here goes the solution:

const result = arrayB.reduce((acc, str) => {

  const found = arrayA.find(item => item.x === str)

    if(found) {
       acc.push(found) 
    } else{
      acc.push({x:str, y:0})
    }

    return acc
},[])

The result should be what you want 🤙🏽

console.log(result) => // [{x:"abc",y:2},{x:"cde",y:3},{x:"efg",y:0},{x:"ghi",y:0},{x:"xyz",y:2}]

With the reduce method you can iterate over arrayB and for each of its items, check if there's an object in arrayA whose property x match the item.

Case yes, just push it up to the result array.

Case no, create a new object { x: < arrayB item >, y: 0 }

Comments

0

preprocess and build a lookup object based on key x and use map on arrayB.

arrayA = [
  { x: "abc", y: 2 },
  { x: "cde", y: 3 },
  { x: "xyz", y: 2 },
];

arrayB = ["abc", "cde", "efg", "ghi", "xyz"];

const lookupA = arrayA.reduce((acc, curr) => ({ ...acc, [curr.x]: curr }), {});
const result = arrayB.map((x) => lookupA[x] ?? { x, y: 0 });

console.log(result)

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.