skip to Main Content

I have 2 arrays – activeDealers and normalDealers.

let normalDealers = [
   { nickname: 'one', inactive: false, dealer: true },
   { nickname: 'two', inactive: false, dealer: false },
   { nickname: 'three', inactive: false, dealer: false }
]

activeDealers = [...normalDealers]

then the normalDealers array should pass through some conditions like this

if (normalDealers.length > 1) {
    const prev = normalDealers.shift();
    normalDealers.push(prev);
}

After this, the normalDealers array will be like this:

[
    { nickname: 'two', inactive: false, dealer: false },
    { nickname: 'three', inactive: false, dealer: false },
    { nickname: 'one', inactive: false, dealer: true }
]

I want to change the normalDealers array’s 0-th index obj value to
- { nickname: 'two', inactive: false, dealer: true }

[
    { nickname: 'two', inactive: false, dealer: true },
    { nickname: 'three', inactive: false, dealer: false },
    { nickname: 'one', inactive: false, dealer: false }
]

But I want the original order of the array inside the activeDealers with updated dealer status value.

Expecting output:

[
    { nickname: 'one', inactive: false, dealer: false },
    { nickname: 'two', inactive: false, dealer: true },
    { nickname: 'three', inactive: false, dealer: false }
]

2

Answers


  1. You can use the unshift method.
    The unshift method inserts new elements at the beginning of an array,
    and the pop method adds new elements to the end of the array, both return the new length of the array.

    if (normalDealers.length > 1) {
        const prev = normalDealers.shift();
        normalDealers.unshift(prev);
    }
    
    Login or Signup to reply.
  2. This should work:

    const activeDealers = [
        { nickname: 'one', inactive: false, dealer: true },
        { nickname: 'two', inactive: false, dealer: false },
        { nickname: 'three', inactive: false, dealer: false }
    ];
    
    const normalDealers = [
        { nickname: 'two', inactive: false, dealer: true },
        { nickname: 'three', inactive: false, dealer: false },
        { nickname: 'one', inactive: false, dealer: false }
    ];
    
    activeDealers.forEach((entryA, indexA) => {
        normalDealers.forEach((entryB, indexB) => {
            if (entryA.nickname === entryB.nickname) {
                activeDealers[indexA] = normalDealers[indexB];
            }
        });
    });
    
    console.log(activeDealers);

    It just replaces the entry with the corresponding nickname in activeDealers with the entry in normalDealers, assuming that each nickname occurs only once. I’m not sure if that’s the best way to achieve what you’re aiming for, though. To determine that, you would have to describe what the meaning behind it is. Why are two arrays needed at all?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search