0

I have the following array (name is always random)

array =
[
{
active: true,
field1: "100",
field2: "",
field3: "1",
name: 0.0020123,
ventasAnuales: "ventasAnuales",
slActive: true
},
{
active: true,
field1: "100",
field2: "",
field3: "1",
name: 0.0020123,
ventasAnuales: "ventasAnuales",
slActive: true
},
{
active: true,
field1: "100",
field2: "",
field3: "1",
name: 0.0020123,
ventasAnuales: "ventasAnuales",
slActive: true
},
{
active: true,
field1: "100",
field2: "",
field3: "1",
name: 0.0020123,
empleados: "empleados",
slActive: true
}
]

Now I want to add extrao objects to the array, and I do it with a concat

array.concat(a).filter(i => i.active)

Problem is that there are certains conditions I should look for before doing the concat. Like for example

  1. If an object with equal field1 and has the same last but one property ventasAnuales | empleados already exists in the array, but field3 is different. It should replace it

For example, given that I want to add the following object

{
active: true,
field1: "100",
field2: "",
field3: "2",
name: 0.0020423,
ventasAnuales: "ventasAnuales",
slActive: true
},

It would replace the first element of the array

  1. If i add an object with the same field3 value, the same last but one property ventasAnuales | empleados and the field1 is different, it should be replaced by the new object.

For example, given that i want to add the following object.

{
    active: true,
    field1: "50",
    field2: "",
    field3: "1",
    name: 0.1020123,
    ventasAnuales: "ventasAnuales",
    slActive: true
    }

It should end up replacing the first element of the array.

How should i write my concat to make this work?

1
  • can you highlight, why you get the item at index zero? Commented Feb 19, 2021 at 8:26

1 Answer 1

1

Just filter the array to find any items that should prevent from insertion. In case you do not find any, add the new item.

you can use [].filter() like so:

const items = […, …, …]
const containing = items.filter(item => item.active == true);
if (containing.length == 0) items.push( … )

but [].every() or [].some() may do as well.

Example with every()

if ( !items.every( i => !i.active )) 
  items.push({ active: false })

In case you need to replace an existing element you can use findIndex() like so:

const items = […, …, …];
const idx = items.findIndex(itm => itm.active);


// create a new item
if (idx < 0) {
  items.push(…)
}
else {
  // update
  items[idx] = …
}
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.