I have data which is an array of arrays.
Each sub-array should hold a maximum of two objects.
I want to add an object (located at position a,b) within this data,
while ensuring that the overall structure remains intact.
If the count of objects is less than 2 within the sub-array
then the new object will be pushed to it.
Otherwise, all other objects will be shifted to the next position.
Can someone please help me write a function to achieve this in javascript/angular
The object to be added is –
var dataToAdd = [
[
{
"name": "OneToThree",
"data": {
"value": 123
}
}
]
]
And array is –
var data = [
[
{
"name": "firstName",
"data": {
"value": 1
}
},
{
"name": "secondName",
"data": {
"value": 2
}
}
],
[
{
"name": "thirdName",
"data": {
"value": 3
}
},
{
"name": "fourthName",
"data": {
"value": 4
}
}
],
[
{
"name": "fifthName",
"data": {
"value": 5
}
}
],
[
{
"name": "sixthname",
"data": {
"value": 6
}
},
{
"name": "seventhName",
"data": {
"value": 7
}
}
]
]
In the above example, only one object is inside the third array. So I can add an object to this array. So, the third array will become –
[
{
"name": "fifthName",
"data": {
"value": 5
}
},
{
"name": "OneToThree",
"data": {
"value": 123
}
}
]
But if I add a new object to the 4th array (at second position, a= 4, b = 2), then the output should be –
var finalData = [
[
{
"name": "firstName",
"data": {
"value": 1
}
},
{
"name": "secondName",
"data": {
"value": 2
}
}
],
[
{
"name": "thirdName",
"data": {
"value": 3
}
},
{
"name": "fourthName",
"data": {
"value": 4
}
}
],
[
{
"name": "fifthName",
"data": {
"value": 5
}
}
],
[
{
"name": "sixthname",
"data": {
"value": 6
}
},
{
"name": "OneToThree",
"data": {
"value": 123
}
}
],
[
{
"name": "seventhName",
"data": {
"value": 7
}
}
]
]
2
Answers
You can achieve this by creating a function that iterates over the
data
array and checks the length of each sub-array. If the length is less than 2, it adds the new object at the end of the sub-array. If the length is 2 or more, it inserts the new object at the specified position a, b and shifts the existing objects accordingly.Demo:
Considering that initial state of array is
empty
, it would be something like this