Remove object inside array items - javascript

I have two array of objects like so:
Main Array:
[
{
"controller": "Education",
"items": [
{
"name": "Insert",
"controller": "Education",
"id": 1
}...etc
]
},
{
"controller": "CustomerPackage",
"items": [
{
"name": "Insert",
"controller": "CustomerPackage",
"id": 1
}..etc
]
}
]
Have the selected list similar as above list.
if there are items in the selected list, I want to remove them from the main array
Here's what I've tried so far, any ideas?
this.mainArray.map(item => {
let subItemId = parseInt(item.items.map(i => i.id));
this.selectedArray.map(v => {
v.items.map(j => {
if (subItemId == j.id) {
console.log("how can i make for mainArray list ");
console.log(j.name);
}
})
})

You need to create an auxiliary variable to get the position of the item in the list you want to delete.
var myArray = [1, 2, 3, 4, 5, 6];
var positionList = -1;
for (var i = 0; i < myArray.length; i++) {
if (myArray[i] == 4)
positionList = i;
}
myArray.splice(positionList, 1);
alert(myArray);
Try it.

Related

How would I filter an array of objects by : If id numbers are consecutive

I have a JSON file that has an array of objects with data inside :
[
{
"_id": "62bd5fba34a8f1c90303055c",
"index": 0,
"email": "mcdonaldholden#xerex.com",
"nameList": [
{
"id": 0,
"name": "Wendi Mooney"
},
{
"id": 2,
"name": "Holloway Whitehead"
}
]
},
{
"_id": "62bd5fbac3e5a4fca5e85e81",
"index": 1,
"nameList": [
{
"id": 0,
"name": "Janine Barrett"
},
{
"id": 1,
"name": "Odonnell Savage"
},
{
"id": 2,
"name": "Patty Owen"
}
]
}, ...
My job is to filter the arrays that have more than two names and if their id are consecutive.
I managed to sort users with more than two user.name but cant grasp the concept of filtering consecutive id numbers
let lister3 = userData.filter(names => names?.nameList?.filter(name => name?.name).length > 2)
Which returns me the objects with more than two user names.
filter takes a function that returns true if you want to retain the item or false if not. In this function, you could check the length of the nameList, and then iterate over its members and make sure their ids are consecutive:
retult = userData.filter(u => {
if (u.nameList.length < 2) {
return false;
}
for (let i = 1; i < u.nameList.length; ++i) {
if (u.nameList[i].id != u.nameList[i - 1].id + 1) {
return false;
}
}
return true;
});
a item should need tow conditions,one is nameList length is two ,the other is the itemId of nameList is consecutive;
so first as you do :
`
let lister3 = userData.filter(names => names?.nameList?.filter(name => name?.name).length > 2)
`
;
then
`
let lister4 = lister3.filter(names=>{
let idOfStr = names.nameList?.sort((a,b)=>a.id-b.id).map(item=>item.id).join("");
let resultStr = Array.from(idOfStr.length).fill(+idOfStr[0]).map((item,index)=>+item+index).join('');
return idOfStr === resultStr
})
`
hope this is useful for you

Looking to filter array and make them into 2 arrays based on a flag if true or false

I am planning to filter an array into 2 separate arrays based on flag in one of the inner arrays but having trouble. Please help me with my code.
How do we get 2 separate arrays out of apiData to have objects filtered in types array based on flag value
var apiData = [{
"id": 1,
"types": [{
"id": "1.1",
"flag": true,
},
"id": "1.2",
"flag": false
}]
},
"id": 2,
"types": [{
"id": "2.1",
"flag": true,
}]
}
]
My Result should be like this for filteredTrueArray [{
"id": 1,
"types": [{
"id": "1.1",
"flag": true,
}]
},
"id": 2,
"types": [{
"id": "2.1",
"flag": true,
}]
}
]
I wanted $scope.filteredTrueArray to have types array with flag=true value objects and another array to have types array with only flag=false objects. Below is my code
$scope.filteredTrueArray = apiData.filter(function(item) {
var isTrueFound = item.types.some(function (el) {
return el.flag == true;
});
if(isTrueFound){
for(var i=0;i<item.types.length>0;i++)
{
if(item.types[i].flag == true){
$scope.filteredTrueArray.push(item.types[i]);
}
}
}
});
I've written a simple filter function. Please take a look!
var apiData = [{
"id": 1,
"types": [{
"id": "1.1",
"flag": true,
}, {
"id": "1.2",
"flag": false
}]
}, {
"id": 2,
"types": [{
"id": "2.1",
"flag": true,
}]
}];
function filterByTypeFlag(records, flagValue) {
var filtered = [];
records.forEach(function (record) {
var matchedTypes = [];
record.types.forEach(function (type) {
if (type.flag === flagValue) {
matchedTypes.push(type);
}
});
if (matchedTypes.length) {
filtered.push({
"id": record.id,
"types": matchedTypes
});
}
});
return filtered;
}
filterByTypeFlag(apiData, true);
filterByTypeFlag(apiData, false);
Here is a sample code that creates an object with a boolean value and creates 2 arrays of objects bases off their boolean value. Sorry if I misunderstood what you were looking for.
var objArray = [];
class testObj {
constructor(Oname, test1) {
this.name = Oname;
this.isABoolean = test1;
objArray.push(this);
}
}
var test1 = new testObj("test1", false);
var test2 = new testObj("test2", true);
var test3 = new testObj("test3", false);
var test4 = new testObj("test4", true);
var test5 = new testObj("test5", false);
var objArray = [test1, test2, test3, test4, test5];
var trueArray = [];
var falseArray = [];
function createArrays() {
for (var i = 0; i < objArray.length; i++) {
if (objArray[i].isABoolean === true) {
trueArray.push(objArray[i]);
//console.log(trueArray[i].name);
} else if (objArray[i].isABoolean === false) {
falseArray.push(objArray[i]);
}
}
}
createArrays();
for (var j = 0; j < trueArray.length; j++) {
console.log("True value: " + trueArray[j].name);
}
for (var k = 0; k < falseArray.length; k++) {
console.log("False value " + falseArray[k].name);
}
EDIT: I cleaned it up to automatically add the objects to an array upon creation.
One solution is to use map() with a filter() for get the new types array.
var apiData = [
{
"id": 1,
"types": [
{"id": "1.1", "flag": true},
{"id": "1.2", "flag": false}
]
},
{
"id": 2,
"types": [
{"id": "2.1", "flag": true}
]
}
];
let filteredTrueArray = apiData.map(
({id, types}) => ({id, types: types.filter(x => x.flag)})
)
.filter(({types}) => types.length);
let filteredFalseArray = apiData.map(
({id, types}) => ({id, types: types.filter(x => !x.flag)})
)
.filter(({types}) => types.length);
console.log("FilteredTrueArray:", filteredTrueArray);
console.log("FilteredFalseArray:", filteredFalseArray);

Add json Elements and values to Multiple json objects

I want combine a JSON object to an ARRAY.
I would like retrieve data from keys finded on var product, and combine score finded to a new variable ( combined results )
combinedresults is what I need. I absolutely don't know how to do this
var product = {
"presentation": 3,
"imgmax": http://test.com/img.jpg,
"puissance": 5,
"efficacite": 4,
"description": "This product is awesome but i need to combine JSON results"
}
var array = [
{
"caracname": "presentation",
"name": "Présentation"
},
{
"caracname": "efficacite",
"name": "Efficacité"
},
{
"caracnam": "puissance",
"name": "Puissance"
}
]
var combinedresults = [
{
"caracname": "presentation",
"name": "Présentation",
"score": 3
},
{
"caracname": "efficacite",
"name": "Efficacité",
"score": 4
},
{
"caracnam": "puissance",
"name": "Puissance",
"score": 5
}
]
Iterate through each item of the array, if the product object contains a key that matches the current items caracname, add it's value as a score.
See below:
var product = {
"presentation": 3,
"imgmax": "http://test.com/img.jpg",
"puissance": 5,
"efficacite": 4,
"description": "This product is awesome but i need to combine JSON results"
}
var array = [
{
"caracname": "presentation",
"name": "Présentation"
},
{
"caracname": "efficacite",
"name": "Efficacité"
},
{
"caracname": "puissance",
"name": "Puissance"
}
]
array.forEach(function(item) {
if (product[item.caracname]) {
item.score = product[item.caracname];
}
});
console.log(array);
Simply map over your current array, extending every object with the score attribute.
array.map(obj => ({...obj, score: product[obj.caracname]}));
If you are not familiar, consider having a look at the spread operator;

Remove JSON object with same id recursively

I have a JSON list with duplicates I need to remove, but I can't find a way to do it.
This is the solution that I have.
I want to keep the first item found with a given ID, and remove the next ones with the same ID.
The problem is, it tries to remove even the first item.
var gindex = [];
function removeDuplicate(list) {
$.each(list, function(i, val){
console.log(val.id);
console.log(gindex);
if($.inArray(val.id, gindex) == -1) { //in array, so leave this item
gindex.push(val.id);
}
else // found already one with the id, delete it
{
list.splice(i, 1);
}
if(val.children) {
val.children = removeDuplicate(val.children);
}
});
return list;
}
gindex = [];
list = removeDuplicate(parsed_list);
console.log(window.JSON.stringify(list));
finally, this is the original list :
[
{
"id": 0,
"children": [
{
"id": 1,
"children": [
{
"id": 2, // with my algorithm, this one get also flagged for deletion
}
]
},
{
"id": 2, // remove this one
},
{
"id": 3,
},
{
"id": 4, // with my algorithm, this one get also flagged for deletion
"children": [
{
"id": 5, // with my algorithm, this one get also flagged for deletion
"children": [
{
"id": 6, // with my algorithm, this one get also flagged for deletion
}
]
}
]
},
{
"id": 5, // remove this one
"children": [
{
"id": 6, // remove this one
}
]
},
{
"id": 6, // remove this one
},
{
"id": 7,
}
]
}
]
and this is the result I would like to obtain
[
{
"id": 0,
"children": [
{
"id": 1,
"children": [
{
"id": 2,
}
]
},
{
"id": 3,
},
{
"id": 4,
"children": [
{
"id": 5,
"children": [
{
"id": 6,
}
]
}
]
},
{
"id": 7,
}
]
}
]
thank you for your reply.
I tried creating my own logic for this (probably more general than what you want), but it may help you debug your code. See the jsFiddle.
The core of the logic is
/**
* Walk through an object or array and remove duplicate elements where the 'id' key is duplicated
* Depends on a seenIds object (using it as a set)
*/
function processData(el) {
// If the element is an array...
if ($.isArray(el)) {
for (var i = 0; i < el.length; i++) {
var value = el[i];
processData(value);
// If the child is now empty, remove it from the array
if (checkForEmpty(value)) {
el.splice(i, 1);
i--; // Fix index after splicing (http://stackoverflow.com/a/9882349/1370556)
}
}
}
// If the element is an object...
else if ($.isPlainObject(el)) {
for (var key in el) {
// Make sure the key is not part of the prototype chain
if (el.hasOwnProperty(key)) {
var value = el[key];
if (key == 'id') {
// If the key has been seen, remove it
if (seenIds[value]) {
delete el[key];
continue; // Skip further processing
} else seenIds[value] = true;
}
processData(value);
// If the child is now empty, remove it from the object
if (checkForEmpty(value)) delete el[key];
}
}
}
}

How can be optimized merging of two arrays of objects?

I would like to optimize my code for CPU and memory consumption. In my function I need to merge two arrays of object into one array. Like UNION, all the ids of the objects in the array have to be unique. I do not want to use third party libraries like Underscore.
This is my function:
var presentation_slides = [
{
"id": "2",
"type": "results"
},
{
"id": "1",
"type": "slide"
},
{
"id": "4",
"type": "questions"
}]
for(var i = 0; i < new_length; i++) {
var my_slide = presentation_slides.filter(function (obj) { return obj.id == i })[0]
if(!my_slide) {
presentation_slides.push({"id": i, "type": "slide"});
}
}
OUTPUT:
var presentation_slides = [
{
"id": "2",
"type": "results"
},
{
"id": "1",
"type": "slide"
},
{
"id": "4",
"type": "questions"
},
{
"id": 0,
"type": "slide"
},
{
"id": 3,
"type": "slide"
}]
Thank you!
EDIT:
Some tests for comparison: http://jsperf.com/how-can-be-optimized-merging-of-two-arrays-of-objects
you can use some instead of filter, i have added a code snipet to your jsperf, which is faster...
check this: .....jsperf.....
for (var i = 0; i < new_length; i++) {
if (!presentation_slides.some(function(obj) { return obj.id == i}))
presentation_slides.push({ "id": i, "type": "slide" });
}
If you just want to merge two arrays, then you can use Array.concat():
var array1 = [
{ id: 1, type: "orange" },
{id: 3, type: "apple" },
{ id: 4, type: "banana" } ],
array2 = [
{ id: 8, type: "strawberry" },
{ id: 9, type: "raspberry" }
];
var array3 = array1.concat(array2);
array3 will contain all the elements from array1 and array2.
This will not check to see if the IDs are unique though.
also, reverse loops are a little faster:
var i = new_length;
while (i--) {
if (!presentation_slides.some(function(obj) { return obj.id == i })) {
presentation_slides.push({ "id": i, "type": "slide" });
}
}
check this ...jspref...

Categories

Resources