Find and replace element in array on the basis of id - javascript

I have an array as follows:
[
{
"id":1,
"active":1,
"name":"paris"
},
{
"id":2,
"active":0,
"name":"london"
},
{
"id":3,
"active":1,
"name":"Australia"
},
{
"id":4,
"active":0,
"name":"india"
}
]
I have a method which recieved a object as argument. object looks something like this:
{
"id":4,
"active":0,
"name":"india"
}
In that method I want to check if element with particular id is present or not. If present I want to replace element in array with the element received in arguments. If element with that id is not found that add that element to the array. How can I do that?

you can do like this
let testArr = [
{
id: 1,
active: 1,
name: "paris",
},
{
id: 2,
active: 0,
name: "london",
},
{
id: 3,
active: 1,
name: "Australia",
},
{
id: 4,
active: 0,
name: "india",
},
];
let testObj = {
id: 4,
active: 0,
name: "india1",
};
let findIndex = testArr.findIndex((data) => data.id === testObj.id);
if (findIndex != -1) {
testArr[findIndex].active = testObj.active;
testArr[findIndex].name = testObj.name;
} else {
testArr = [...testArr, testObj];
}
console.log("testArr=>", testArr);

I'd propose the following: in any case you want to have the new object included in the given array:
Remove Object with id from array
Add new Object
Could work as following:
let testArr = [ ... ]
let testObj = { ... }
testArr = testArr.filter(element => element.id !== testObj.id)
testArr.push(testObj)
If it's necessary to keep the object in the array:
let testArr = [ ... ]
let testObj = { ... }
const foundElement = testArr.find(element => element.id === testObj.id)
if (foundElement) {
foundElement.active = testObj.active
foundElement.name = testObj.name
} else {
testArr.push(testObj)
}

you can do something like this
const update = (data, item) => {
const withId = data.reduce((res, curr) => ({
...res,
[curr.id]: curr
}), {})
withId[item.id] = item
return Object.values(withId)
}
let testArr = [
{
id: 1,
active: 1,
name: "paris",
},
{
id: 2,
active: 0,
name: "london",
},
{
id: 3,
active: 1,
name: "Australia",
},
{
id: 4,
active: 0,
name: "india",
},
];
let testObj = {
id: 4,
active: 0,
name: "india1",
};
const updated = update(testArr, testObj)
console.log(updated)

Related

How to sort array with selected list in javascript?

I have a list look like:
const initArray = [
{
id: 0,
},
{
id: 1,
},
{
id: 2,
},
{
id: 3,
},
];
A selected list look like:
const selectedList = [
{
id: 2,
},
];
And the desired data has been sorted:
const outPut= [
{
id: 2,
},
{
id: 0,
},
{
id: 1,
},
{
id: 3,
},
];
I'm in trouble right now, so I can't figure it out yet.
Can you share some solutions?
You could take an object which keeps the order of the first objects and sort the rest after.
const
data = [{ id: 0 }, { id: 1 }, { id: 2 }, { id: 3 }],
selectedList = [{ id: 2 }],
order = Object.fromEntries(selectedList.map(({ id }, i) => [id, i + 1]));
data.sort((a, b) => (order[a.id] || Number.MAX_VALUE) - (order[b.id] || Number.MAX_VALUE));
console.log(data);
Using Set and Array#map, get set of ids to prioritize
Using Array#sort, sort the items using the above set
const _sort = (arr = [], selected = []) => {
const priority = new Set( selected.map(({ id }) => id) );
return [...arr].sort(({ id: a }, { id: b }) => priority.has(b) - priority.has(a));
}
const
initArray = [ { id: 0 }, { id: 1 }, { id: 2 }, { id: 3 } ],
selectedList = [ { id: 2 } ];
console.log( _sort(initArray, selectedList) );

Vue.js - Filter array of JSONs by another array of JSONs

I have an array of JSONs called products and another one called deletedProducts.
I want to filter those products that are not in deletedProducts.
Example:
products = [
{
id: 1,
name: 'Box'
},
{
id: 2,
name: 'Lamp'
}
]
deletedProducts = [
{
id: 1,
name: 'Box'
}
]
Result should be like this:
result = [
{
id: 2,
name: 'Lamp'
}
]
try filter and find methods :
let result =products.filter(prod=>{
return !deletedProducts.find(dprod=>{
return dprod.id===prod.id;
})
})
let products = [{
id: 1,
name: 'Box'
},
{
id: 2,
name: 'Lamp'
}
]
let deletedProducts = [{
id: 1,
name: 'Box'
}]
let result = products.filter(prod => {
return !deletedProducts.find(dprod => {
return dprod.id === prod.id;
})
})
console.log(result)
try this comparer function and filter. (reference by array of element "id" on this exmaple)
let products = [
{
id: 1,
name: 'Box'
},
{
id: 2,
name: 'Lamp'
}
]
let deletedProducts = [
{
id: 1,
name: 'Box'
}
]
function comparer(otherArray){
return function (current) {
return otherArray.filter(function(other) {
return other.id === current.id
}).length===0;
}
}
var result=products.filter(comparer(deletedProducts ));
console.log(result);

Filter an object iside an array

I need to delete entire object that do not have passed
here is the array
const array = [{
course: 1,
list: [{
id: 1,
name: "john",
code: true
},
{
id: 1,
name: "maria",
code: true
},
]
},
{
course: 2,
list: [{
id: 3,
name: "rose"
},
{
id: 4,
name: "mark",
code: true
}
]
}
]
That i need is remove obj that not have code:true, and get this
const array = [{
course: 1,
list: [{
id: 1,
name: "john",
code: true
}, ]
},
{
course: 2,
list: [{
id: 1,
name: "mark",
code: true
}]
}
]
I tried to make a map inside a filter, but it does not work at all
const remove = array.filter(function(lines) {
return lines.map(line => line.list.map(list => list.code))
});
You can map through the array, then copy all properties of the specific item and separately do the filtering on the list attribute.
const array = [{
course: 1,
list: [{
id: 1,
name: "john",
code: true
},
{
id: 1,
name: "maria",
code: true
},
]
},
{
course: 2,
list: [{
id: 3,
name: "rose"
},
{
id: 4,
name: "mark",
code: true
}
]
}
]
const filter = arr => arr.map(arrItem => ({
...arrItem,
list: arrItem.list.filter( listItem => listItem.code )
})
)
console.log( filter(array) )
const filtered = [];
arr.forEach(item => {
const list = item.list.filter(listItem => listItem.code);
if(list.length > 0) {
filter.push({ ...item, list });
}
});
This approach will only add items to the filtered output array if the list contains any items after filtering out those with code: false. To include them anyway, you could do:
const filtered = arr.map(item => ({
...item,
list: item.list.filter(listItem => listItem.code)
});

Pull key from Array of Objects Dynamically And Transform to Array of Objects

I have a specific case and I don't even know if it is possible to achieve.
Given the input array.
var originalArr = [
[
{ ID: 3, name: 'Beef' },
{ ID: 4, name: 'Macaroni' },
{ ID: 5, name: 'Sauce#1' }
],
[{ ID: 1, name: 'Lettuce' }, { ID: 2, name: 'Brocoli' }]
];
I would like to iterate over the inner arrays and pick the ID's from objects then create new one in place of array. So my output should look something like this.
var output = [
{
'1': {
name: 'Lettuce',
ID: 1
},
'2': {
name: 'Brocoli',
ID: 2
}
},
{
'3': {
name: 'Beef',
ID: 3
},
'4': {
name: 'Macaroni',
ID: 4
},
'5': {
name: 'Sauce#1'
}
}
];
It is easy to iterate over the inner arrays with map but how can I create new Object in place of the array and have its key value dynamically pulled up ? And is it even possible given my input to produce the desired output.
Use map and reduce
originalArr.map( s => //iterate outer array
s.reduce( (acc, c) => ( //iterate inner array using reduce
acc[c.ID] = c, acc //assign the id as key to accumulator and return the accumulator
) , {}) //initialize accumulator to {}
)
Demo
var originalArr = [
[
{ ID: 3, name: 'Beef' },
{ ID: 4, name: 'Macaroni' },
{ ID: 5, name: 'Sauce#1' }
],
[{ ID: 1, name: 'Lettuce' }, { ID: 2, name: 'Brocoli' }]
];
var output = originalArr.map( s => s.reduce( (acc, c) => ( acc[c.ID] = c, acc ) , {}) );
console.log(output);
You can achieve using recursion with pure javascript
var originalArr = [
[{
ID: 3,
name: 'Beef'
}, {
ID: 4,
name: 'Macaroni'
}, {
ID: 5,
name: 'Sauce#1'
}],
[{
ID: 1,
name: 'Lettuce'
}, {
ID: 2,
name: 'Brocoli'
}]
]
function bindInObject(object, array) {
for (var i = 0; i < array.length; i++) {
var it = array[i];
if (it instanceof Array) {
bindInObject(object, it);
} else {
var id = it.ID;
object[id] = it;
}
}
}
var output = {};
bindInObject(output, originalArr);
console.log(output)
const original_array = [
[
{ ID: 3, name: 'Beef' },
{ ID: 4, name: 'Macaroni' },
{ ID: 5, name: 'Sauce#1' }
],
[
{ ID: 1, name: 'Lettuce' },
{ ID: 2, name: 'Brocoli' }
]
]
let new_array = []
for (let i=0; i < original_array.length; i++) {
if (original_array[i + 1]) new_array =
new_array.concat(original_array[i].concat(original_array[i+1]))
}
let output = []
for (let i=0; i<new_array.length; i++) {
output.push({[new_array[i].ID]: new_array[i]})
}

Removing duplicate array values and then storing them [react]

I'm trying to strip the duplicate array values from my current array. And I'd like to store the fresh list (list without duplicates) into a new variable.
var names = ["Daniel","Lucas","Gwen","Henry","Jasper","Lucas","Daniel"];
const uniqueNames = [];
const namesArr = names.filter((val, id) => {
names.indexOf(val) == id; // this just returns true
});
How can I remove the duplicated names and place the non-duplicates into a new variable?
ie: uniqueNames would return...
["Daniel","Lucas","Gwen","Henry","Jasper"]
(I'm using react jsx) Thank you!
You can do it in a one-liner
const uniqueNames = Array.from(new Set(names));
// it will return a collection of unique items
Note that #Wild Widow pointed out one of your mistake - you did not use the return statement. (it sucks when we forget, but it happens!)
I will add to that that you code could be simplified and the callback could be more reusable if you take into account the third argument of the filter(a,b,c) function - where c is the array being traversed. With that said you could refactor your code as follow:
const uniqueNames = names.filter((val, id, array) => {
return array.indexOf(val) == id;
});
Also, you won't even need a return statement if you use es6
const uniqueNames = names.filter((val,id,array) => array.indexOf(val) == id);
If you want to remove duplicate values which contains same "id", You can use this.
const arr = [
{ id: 2, name: "sumit" },
{ id: 1, name: "amit" },
{ id: 3, name: "rahul" },
{ id: 4, name: "jay" },
{ id: 2, name: "ra one" },
{ id: 3, name: "alex" },
{ id: 1, name: "devid" },
{ id: 7, name: "sam" },
];
function getUnique(arr, index) {
const unique = arr
.map(e => e[index])
// store the keys of the unique objects
.map((e, i, final) => final.indexOf(e) === i && i)
// eliminate the dead keys & store unique objects
.filter(e => arr[e]).map(e => arr[e]);
return unique;
}
console.log(getUnique(arr,'id'))
Result :
[
{ id: 2, name: "sumit" },
{ id: 1, name: "amit" },
{ id: 3, name: "rahul" },
{ id: 4, name: "jay" },
{ id: 7, name: "sam" }
]
you forgot to use return statement in the filter call
const namesArr = duplicatesArray.filter(function(elem, pos) {
return duplicatesArray.indexOf(elem) == pos;
});
Since I found the code of #Infaz 's answer used somewhere and it confused me greatly, I thought I would share the refactored function.
function getUnique(array, key) {
if (typeof key !== 'function') {
const property = key;
key = function(item) { return item[property]; };
}
return Array.from(array.reduce(function(map, item) {
const k = key(item);
if (!map.has(k)) map.set(k, item);
return map;
}, new Map()).values());
}
// Example
const items = [
{ id: 2, name: "sumit" },
{ id: 1, name: "amit" },
{ id: 3, name: "rahul" },
{ id: 4, name: "jay" },
{ id: 2, name: "ra one" },
{ id: 3, name: "alex" },
{ id: 1, name: "devid" },
{ id: 7, name: "sam" },
];
console.log(getUnique(items, 'id'));
/*Output:
[
{ id: 2, name: "sumit" },
{ id: 1, name: "amit" },
{ id: 3, name: "rahul" },
{ id: 4, name: "jay" },
{ id: 7, name: "sam" }
]
*/
Also you can do this
{Array.from(new Set(yourArray.map((j) => j.location))).map((location) => (
<option value={`${location}`}>{location}</option>
))}

Categories