This question already has answers here:
How can I remove a specific item from an array in JavaScript?
(142 answers)
Closed 7 years ago.
I have an array of objects:
var myArr;
Let’s say that on page load it contains 10 objects with the following structure:
{
Id: …,
Name: …
}
How can I remove an object from myArr by its Id?
Try like this
var id = 2;
var list = [{
Id: 1,
Name: 'a'
}, {
Id: 2,
Name: 'b'
}, {
Id: 3,
Name: 'c'
}];
var index = list.map(x => {
return x.Id;
}).indexOf(id);
list.splice(index, 1);
console.log(list);
JSFIDDLE
Or you can utilize .filter()
Like this
var id = 2;
var list = [{
Id: 1,
Name: 'a'
}, {
Id: 2,
Name: 'b'
}, {
Id: 3,
Name: 'c'
}];
var lists = list.filter(x => {
return x.Id != id;
})
console.log(lists);
DEMO
Two solutions, one evolve creating new instance and one changes the instance of your array.
Filter:
idToRemove = DESIRED_ID;
myArr = myArr.filter(function(item) {
return item.Id != idToRemove;
});
As you can see, the filter method returns new instance of the filtered array.
Second option is to find the index of the item and then remove it with splice:
idToRemove = DESIRED_ID;
index = myArr.map(function(item) {
return item.Id
}).indexOf(idToRemove);
myArr.splice(index, 1);
can you try
newArray = myArr
.filter(function(element) {
return element.id !== thisId;
});
Related
This question already has answers here:
How to filter object array based on attributes?
(21 answers)
Closed 1 year ago.
I have the following array of objects, I want to loop through it and filter based on the id or code that I pass into the function.
state.products = [{id = 1, name = Bottle},{id = 2, name = umbrella}, {id = 3, name = shoe}]
const getVal = (id)=> {
const av = state.products.filter((s) s.productId == id)
}
The following doesn't seem to iterate through the array and check through each object? I am getting an empty array for console.log(av)
You are on a right way, but you are not using Array.filter properly.
And also the provided array of object is not also in a good format. Object should be in a key:value pairs.
state.products = [
{ id: 1, name: "Bottle" },
{ id: 2, name: "umbrella" },
{ id: 3, name: "shoe" }
]
const getAllArrayExcept = (id) => {
// this will return all the array except provided id
return state.products.filter((s) => s.id !== id)
}
const getOnlyArray = (id) => {
// this will return only item which match the provided id
return state.products.filter((s) => s.id === id)
}
console.log(getAllArrayExcept(1))
/*
output: [{ id = 2, name = umbrella }, { id = 3, name = shoe }]
*/
console.log(getOnlyArray(1))
/*
output: [{ id = 1, name = Bottle }]
*/
Here is the working snippet:
const products = [
{ id: 1, name: "Bottle" },
{ id: 2, name: "umbrella" },
{ id: 3, name: "shoe" }
]
const getAllArrayExcept = (id) => {
// this will return all the array except provided id
return products.filter((s) => s.id !== id)
}
const getOnlyArray = (id) => {
// this will return only item which match the provided id
return products.filter((s) => s.id === id)
}
console.log("All array except: ", getAllArrayExcept(1))
console.log("Only provided item in array: ", getOnlyArray(1))
This question already has answers here:
Move an array element from one array position to another
(44 answers)
Closed 2 years ago.
I have an array of objects with this format
let arr = [ { name: "test1", id: 5}, { name: "test2", id: 6 } , { name: "test3", id: 8 } ]
Now I basically want to move the item with 6 to the front of the array by re-arranging so that result becomes
let result = [ { name: "test2", id: 6 } , { name: "test1", id: 5}, { name: "test3", id: 8 } ]
What I have tried
const found = arr.find((element) => {
return element.id === 6;
});
if (found) {
const [...arr, found] = arr;
return found;
} else {
return arr;
}
You can make use of Array.unshift and Array.splice.
let arr = [{name:"test1",id:5},{name:"test2",id:6},{name:"test3",id:8}]
const moveToFront = (data, matchingId) => {
//find the index of the element in the array
const index = data.findIndex(({id}) => id === matchingId);
if(index !== -1) {
//if the matching element is found,
const updatedData = [...data];
//then remove that element and use `unshift`
updatedData.unshift(...updatedData.splice(index, 1));
return updatedData;
}
//if the matching element is not found, then return the same array
return data;
}
console.log(moveToFront(arr, 6));
.as-console-wrapper {
max-height: 100% !important;
}
You could sort the array with the delta of the checks.
const
array = [{ name: "test1", id: 5 }, { name: "test2", id: 6 }, { name: "test3", id: 8 }];
array.sort((a, b) => (b.id === 6) - (a.id === 6));
console.log(array);
const array = [{ name: "test1", id: 5 }, { name: "test2", id: 6 }, { name: "test3", id: 8 }];
const sortedArray = array.sort((a, b) => (b.id === 6) - (a.id === 6)); console.log(sortedArray);
discusses an easy way to sort your JavaScript Array by the order of the index number for each item in the Array object. This can be helpful if you want to sort alphabetically and not need to create a new String Array with a function like String.sort().
A quick tip that can be useful to you if you want a quick solution to sorting an Array in JavaScript is below.Remember that it is always best practice to use the Array methods built into the language. They are created to work fast and efficient. However, if you really want to sort your array by index number and not have an array of strings, then this article will be for you.:
String→Number: When a function returns a Number value, then JavaScript interprets it as being equal to the Number value in the code...The function is used by passing two parameters, which should return true when they are equal and false when they are not equal.In this case, we are sort of reverse comparing them. We are checking the ID of the items inside the Array to see if they match, but we subtract one to check if they are less than. This is because when we call .sort(), JavaScript is sorting alphabetically and an ID with a value of 6 will be at the end of the list. So, a value of -1 will make it appear in the correct order.If you want to use this method for your Array, then please add a comment below!
You can use Array.unshift() to add element to the beginning of the array and Array.splice() to remove the array element.
let arr = [ { name: "test1", id: 5}, { name: "test2", id: 6 } , { name: "test3", id: 8 } ]
let result = [...arr];
const index = result.findIndex(e => e.id === 6)
result.unshift(result.splice(index, 1)[0])
console.log(result);
You can make use of filter and unshift
let arr = [{ name: "test1", id: 5 },{ name: "test2", id: 6 },{ name: "test3", id: 8 }];
let firstObject;
let result = arr.filter((value) => {
if (value.id != 6) return value;
firstObject = value;
});
result.unshift(firstObject);
console.log(result);
I created a sample code to demo my problem, the actual data is much bigger
const arr = [{
id: 1
}, {
id: 2,
items: [{
id: 1
}]
}]
const target = 2
const nextIndex = 1
newArr = arr.map(o => o.id === target ? ({
...o,
items: [...o.items, {
id: 'new id'
}]
}) : o);
console.log(newArr);
How to insert {id: 'new id'} by index? Above code is appending onto items array. Assuming I have a click event, user can insert the position of {id: 'new id} by index, I can't use append as it doesn't replace existing object.
expected output
[{
id: 1
}, {
id: 2,
items: [{
id: 1
},{
id: 'something'
}]
Above code doesn't work, adding new item to items array without using index.
Try to pass index from onClick event
functionName = (i) => { //where i is index from onclick event
arr.map( o, index) => {
if(i === index)
{
const obj = { //object
id: 'new id'
}
arr[i].push(obj) // push object at given index from onClick
}
}
}
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements
const target = 2;
int index = arr.findIndex(v => v.id == target);
if (index > -1) {
arr.splice(index, 1, {id: 'new id'}); // replace 1 with 0 if you just want to insert.
}
This question already has answers here:
How to get the difference between two arrays of objects in JavaScript
(22 answers)
check the difference between two arrays of objects in javascript [duplicate]
(3 answers)
Closed 3 years ago.
I have two identical arrays of objects.
I then add an object to one of the arrays at a random index:
Arr1 = [{ id: "a" }, { id: "b" }, { id: "c" }]
Arr2 = [{ id: "a" }, { id: "d" }, { id: "b" }, { id: "c" }]
How would I go about comparing the two arrays, extracting that new object from Arr2 and assigning that object to a constant?
This is my best effort:
const newPlan
if (state.plans.length !== data.allPlansJson.edges.length) {
data.allPlansJson.edges.map(staticPlan => {
state.plans.map(planInState => {
planInState !== staticPlan && newPlan = staticPlan
})
})
}
Too add even more context:
I'm getting objects from the array data.allPlansJson.edges and spreading them in my a database collection. I'm then getting all of those objects and putting them back into an array in my redux state.
This function is to detect when there is a new object added to the data.allPlansJson.edges array and execute a redux action that posts this new object to my database collection.
For this specific scenario, in order to get just the new items you can filter out any points that are in the orignial.
const arrA = [{ id: "a" }, { id: "b" }, { id: "c" }];
const arrB = [{ id: "a" }, { id: "d" }, { id: "b" }, { id: "c" }];
const newItems = arrB.filter(b => !arrA.some(a => a.id === b.id));
arrB.filter loops over arrB calling the arrow function. To keep an item we return true in this callback. To get rid of an item we return false.
arrA.some loops over arrA calling the provided arrow function. The function will resolve true if any of the items return true. Since we are matching for items found in the array we add the ! before arrA.some in order to find items not found
You can now grab the first item from newItems by doing
const [someConst] = newItems;
Note: this is a one-way search. If there are new ones in arrA they will not be found
You could find the object by checking the object with with the one at the same index.
var array1 = [{ id: "a" }, { id: "b" }, { id: "c" }],
array2 = [{ id: "a" }, { id: "d" }, { id: "b" }, { id: "c" }],
inserted = array2.find((o, i) => o.id !== array1[i].id);
console.log(inserted);
Arr1 = [{ id: "a" }, { id: "b" }, { id: "c" }];
Arr2 = [{ id: "a" }, { id: "d" }, { id: "b" }, { id: "c" }];
function findExtra(arr1, arr2) {
len1 = arr1.length;
len2 = arr2.length;
for (i = 0; i < Math.min(len1, len2); i++) {
if (arr1[i].id !== arr2[i].id) { // Compare elements pairwise
return len1 > len2 ? arr1[i] : arr2[i]; // Return the newly added one
}
}
// The new element is the last one
return len1 > len2 ? arr1[len1 - 1] : arr2[len2 - 1];
}
console.log(findExtra(Arr1, Arr2));
Is this what you are looking for?
Let's say I have an array as follows:
types = ['Old', 'New', 'Template'];
I need to convert it into an array of objects that looks like this:
[
{
id: 1,
name: 'Old'
},
{
id: 2,
name: 'New'
},
{
id: 3,
name: 'Template'
}
]
You can use map to iterate over the original array and create new objects.
let types = ['Old', 'New', 'Template'];
let objects = types.map((value, index) => {
return {
id: index + 1,
name: value
};
})
You can check a working example here.
The solution of above problem is the map() method of JavaScript or Type Script.
map() method creates a new array with the results of calling
a provided function on every element in the calling array.
let newArray = arr.map((currentvalue,index,array)=>{
return Element of array
});
/*map() method creates a new array with the results of calling
a provided function on every element in the calling array.*/
let types = [
'Old',
'New',
'Template'
];
/*
let newArray = arr.map((currentvalue,index,array)=>{
return Element of array
});
*/
let Obj = types.map((value, i) => {
let data = {
id: i + 1,
name: value
};
return data;
});
console.log("Obj", Obj);
Please follow following links:
TypeScript
JS-Fiddle
We can achieve the solution of above problem by for loop :
let types = [
"One",
"Two",
"Three"
];
let arr = [];
for (let i = 0; i < types.length; i++){
let data = {
id: i + 1,
name: types[i]
};
arr.push(data);
}
console.log("data", arr);