I have an array of objects. Then I want to add another object and stick it to the one that already existed in my array. Which means the index of the new object should be larger by one in relation to my already existed object and rest of the element's indexes should be incremented by one.
For example:
I tried to split my array into two starting from index = 2, push my new element, and then join and again but my code do not work well.
for (var i in myArray) {
if (myArray[i].name === inheritedRate.inherit) {
var tempArr = [];
for (var n = i; n < myArray.length; n++) {
tempArr.push($scope.myArray[n]);
myArray.splice(n, 1);
}
myArray.push(inheritedRate);
myArray.concat(tempArr);
}
}
in other words I have an array which looks like this:
myArray = [
{name: "not selected"},
{name: "not selected"},
{name: "selected"},
{name: "not selected"},
{name: "not selected"},
{name: "not selected"},
]
And I want to put there an external element to make it look this:
myArray = [
{name: "not selected"},
{name: "not selected"},
{name: "selected"},
{name: "new element"}, // inserted
{name: "not selected"},
{name: "not selected"},
{name: "not selected"},
]
Duplicate elements can be found using two loops. The outer loop will iterate through the array from 0 to length of the array. The outer loop will select an element. The inner loop will be used to compare the selected element with the rest of the elements of the array.
With ES6, we have a javascript Set object which stores only unique elements. A Set object can be created with array values by directly supplying the array to its constructor. If the array has duplicate values, then they will be removed by the Set. This means that the Set will only contain unique array elements.
Use the filter() method: The filter() method creates a new array of elements that pass the condition we provide. It will include only those elements for which true is returned. We can remove duplicate values from the array by simply adjusting our condition.
To remove duplicates from an array: First, convert an array of duplicates to a Set . The new Set will implicitly remove duplicate elements. Then, convert the set back to an array.
If I understood you right, the problem for you is to how to insert and move elements in array. You can do it with splice method, which has optional parameters for elements to insert:
Here is what you need for your example:
var myArray = [
{name: "not selected"},
{name: "not selected"},
{name: "selected"},
{name: "not selected"},
{name: "not selected"},
{name: "not selected"}
];
myArray.splice(3, 0, {
name: "new element"
});
console.log(myArray);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With