How to push values to new array by comparing 2 arrays - javascript

I have 2 arrays.
selectedgroup = [ ID:1, selected:true,
ID:2, selected:false,
..... ]
The 2nd array is,
mainarr=[ ID:1, mainid:25, name:ser, pID:545,
ID:2, mainid:84, name:ferdi, pID:678,
ID:3, mainid:88, name:ferSER, pID:656,
....]
I want to check if mainarr contains an element of selectedgroup. The unique id in both arrays is ID . Then I want to push it on a new array.
How can I do this?

Assuming your array is in following valid format. Iterate over your mainarr and check if ID of mainarr matches the ID of selectedgroup array then simply push the object into new array. Like following:
var selectedgroup = [ {ID:1, selected:true},{ID:2, selected:false} ];
var mainarr = [ {ID:1, mainid:25, name:'ser', pID:545},{ID:2, mainid:84, name:'ferdi', pID:678},{ID:3, mainid:88, name:'ferSER', pID:656}];
var newArray = [];
mainarr.forEach(function(mainObject) {
for (let i=0; i<selectedgroup.length; i++){
if(selectedgroup [i].ID === mainObject.ID){
newArray.push(mainObject);
}
}
});
console.log(newArray);

Try this
var newarr =[];
for(i=0; i<mainarr.length; i++){
for(j=0;j<selectedgroup.length; j++){
if(mainarr[i].ID = selectedgroup[j].ID)
{
newarr.push(mainarr[i]);
}
}
}

I think use of filter, is a better method than use of forEach. So I just include this solution for reference.
var selectedgroup = [ {ID:1, selected:true},{ID:2, selected:false} ];
var mainarr = [ {ID:1, mainid:25, name:'ser', pID:545},{ID:2, mainid:84, name:'ferdi', pID:678},{ID:3, mainid:88, name:'ferSER', pID:656}];
const selectedgroupIds = selectedgroup.map(selected => selected.ID);
const newarr = mainarr.filter(main => {
return selectedgroupIds.indexOf(main.ID) !== -1;
})

Array.prototype.filter() method creates a new array with all elements that pass the test implemented by the provided function. Like following:
var selectedgroup = [ {ID:1, selected:true},{ID:2, selected:false} ];
var mainarr = [ {ID:1, mainid:25, name:'ser', pID:545},{ID:2, mainid:84, name:'ferdi', pID:678},{ID:3, mainid:88, name:'ferSER', pID:656}];
var newarr = mainarr.filter(function(eachArr){
for (var i = 0; i < selectedgroup.length; i++){
if(selectedgroup [i].ID === eachArr.ID){
return true;
} }})
If selectedgroup array can have many values, you can use map to get all ids first to avoid inner loop and then filter with them as #CHANist said.
For your reference: Array.prototype.map().
Thus, the code would become
var selectedgroup = [ {ID:1, selected:true},{ID:2, selected:false} ];
var mainarr = [ {ID:1, mainid:25, name:'ser', pID:545},{ID:2, mainid:84, name:'ferdi', pID:678},{ID:3, mainid:88, name:'ferSER', pID:656}];
var ids = selectedgroup.map(function(obj){ return obj.ID});
var newarr = mainarr.filter(function(eachArr){
for (var i = 0; i < selectedgroup.length; i++){
if(ids.indexOf(eachArr.ID) !== -1){
return true;
} }})

Use below code,
var selectedgroup = [
{ID:1, selected:true},
{ID:2, selected:false}
];
var mainarr = [
{ID:1, mainid:25, name:'ser', pID:545},
{ID:2, mainid:84, name:'ferdi', pID:678},
{ID:3, mainid:88, name:'ferSER', pID:656}
];
var newArray=[];
for (var i = 0, l2 = mainarr .length; i < l2; i++) {
for (var j = 0, l1 = selectedgroup .length; j < l1; j++) {
if(mainarr [i].ID===selectedgroup [j].ID){
newArray.push(mainarr [i]);
}
}
}
console.log(newArray);

Related

Is there a way to iterate over an Object based upon the length of an array?

I have this array ["12345678", "87654321"]
And I want to inject each index into an object in the itemId category and loop over the object again placing the second index into another itemId category.
var myArray = ["12345678", "87654321", "12345678"]
var idArray =[]
var arrayLength = myArray.length;
for (var i =0; i < arrayLength; i++) {
let idElement = myArray[i]
idArray.push(idElement);
console.log(idElement);
let multipleitems = {
Request: {
Details: {
id: idArray,
amount: 1
},
}
};
Gives me this output
Request: {Details: {Id: ["12345678", "12345678", "12345678" ], amount: 1}}
Is it possible to iterate over "details however many times based upon how many indexes are in myArray to get this output
{"Request":{"Details":[{"Id":"12345678","amount":1},{"itemId":"87654321","amount":1},{"Id":"12345678","amount":1}]}}
This is a very basic array map() operation. You return a new object every iteration and map() itself returns a new array
var myArray = ["12345678", "87654321", "12345678"];
let multipleitems = {
Request: {
Details: myArray.map(id => ({id, amount:1}) )
}
};
console.log(multipleitems)

Trim Array value from specific char to specific char

How to get specific value from array?
i.e.
"Names": [
"Name[name]",
"Result[Type]",
"Validation[Option]",
"Status[Pointer]"
]
Output must be:
"Names": [
"name",
"Type",
"Option",
"Pointer"
]
Try like this:
export class AppComponent {
Names = [
"Name[name]",
"Result[Type]",
"Validation[Option]",
"Status[Pointer]"
]
constructor() {
var modifiedNames = this.Names.map(x => x.split('[').pop().split(']')[0])
console.log(modifiedNames)
}
}
See Stackbiltz Demo
const array = [
"Name[name]",
"Result[Type]",
"Validation[Option]",
"Status[Pointer]"
];
const newArray = array.map(e => /^\w+\[(\w+)\]$/.exec(e)[1]);
// ["name", "Type", "Option", "Pointer"]
You can use substring method and based on the start and end bracket grab the subtring. To iterate on every element of array use map function, it creates a new array with the results of calling a provided function on every element in the calling array.
const arr = [
"Name[name]",
"Result[Type]",
"Validation[Option]",
"Status[Pointer]"
]
let result = arr.map((a)=>{ return a.substring(a.indexOf("[") + 1 , a.indexOf("]")) });
console.log(result);
You can loop through array and using following regex to get the desired output.
const array = [
"Name[name]",
"Result[Type]",
"Validation[Option]",
"Status[Pointer]"
];
var regexTest = new RegExp(/\[([^\]]+)\]/);
var newArray = array.map(e => regexTest.exec(e)[1]);
fiddle link
substring and indexOf in action:
let newArray = [];
for(var i=0; i<array.length; i++){
var s = array[i];
var n = s.indexOf('[');
s = s.substring(n+1, s.length-1);
newArray.push(s);
}
OR
let newArray = [];
for(var i=0; i<array.length; i++){
newArray.push(array[i].substring(array[i].indexOf('[')+1, array[i].length-1));
}

combine multiple list to single array

{ "data": [ {"firstName": "Achmad"}, {"lastName": "a"} ] } and this my script var body = request.body;for(var i = 0;i < body.data.length;i++){var obj = body.data[i];var keyes = Object.keys(obj);} the problem response from var keyes = Object.keys(obj); is list like this [ 'firstName' ] [ 'lastName' ] i'm wanna like this ['firstName', 'lastName']
Thanks before.
Assuming each of the arrays are elements of a parent array, one way you could achieve this is by using Array.prototype.reduce:
const flat = [
["aku"],
["dia"],
["ia"]
].reduce((accum, el) => accum.concat(el), [])
console.log(flat);
EDITED: You could concat each item of your array :
const body = {
"data": [
{"firstName": "Achmad"},
{"lastName": "a"}
]
};
let result = [];
for (item of body.data) {
result = result.concat(Object.keys(item));
}
console.log(result); // -> ['firstName', 'lastName']
Maybe you want to do something like this
var body = request.body;
var keyes = [];
for(var i = 0; i < body.data.length; i++){
var obj = body.data[i];
keyes.push( Object.keys(obj) );
}

Why this array producer code doesn't work as it shows?

I have used some code as bellow to produce new array from tow arrays :
var arr1 = [['wo','ss'],['er','me'], ['lo','to']];
var arr2 = [['mine','yours'],['from', 'theme']];
var arr3 = [];
var temp = [];
//this will be an array of arrays that every index is arr2 + one index from arr1
var end = [];
arr1.forEach(function(item) {
temp = arr2;
temp.push(item);
end.push(temp);
})
console.log(end)
But after the result is not my desired and is not logical
[
['mine','yours'], ['from','theme'], ['wo', 'ss'],
['mine', 'yours], ['from','theme'], ['er', 'me'],
['mine', 'yours], ['from','theme'], ['lo', 'to']
]
You must clone the arr2 for each iteration defining temp as new array each time
var arr1 = [['wo','ss'],['er','me'], ['lo','to']];
var arr2 = [['mine','yours'],['from', 'theme']];
var arr3 = [];
var end = [] //this will be an array of arrays that every index is arr2 + one index from arr1
arr1.forEach(function(item) {
var temp = arr2.slice();
temp.push(item);
end.push(temp);
})
console.log(end);
This code works as you expected
In your code Array#push method will push values to arr2 which update the array(since temp is reference to array arr2) on each iteration.
Use Array#concat method which generates a new concatenated array although Array#map can be used for generating the array.
var arr1 = [
['wo', 'ss'],
['er', 'me'],
['lo', 'to']
];
var arr2 = [
['mine', 'yours'],
['from', 'theme']
];
var end = arr1.map(function(item) {
return arr2.concat([item]);
})
console.log(JSON.stringify(end))
UPDATE : Currently it creates the reference to the parent array updating one will change other. if you want a new array with the element then do it with Array#map and Array#slice methods .
var arr1 = [
['wo', 'ss'],
['er', 'me'],
['lo', 'to']
];
var arr2 = [
['mine', 'yours'],
['from', 'theme']
];
var end = arr1.map(function(item) {
return arr2.map(function(v) {
return v.slice();
}).concat([item.slice()]);
})
console.log(end)

Getting only values from object literal

Going on from this question: Getting first object from javascript litteral
Would it be possible to get only the values from a group of name:value pairs? So lets say we have a list of objects, each object having any number of values:
var items = [
{name:"Foo", age:16, gender:"m"},
{name:"Bar", age:17, gender:"f"},
{name:"foo", age:16, gender:"m"},
{name:"bar", age:18, gender:"m"},
{name:"foobar", age:18, gender:"f"},
{name:"barfoo", age:20, gender:"f"}
];
How can I return a list like:
var items = [
["Foo", 16, "m"],
["Bar", 17, "f"],
["foo", 16, "m"],
["bar", 18, "m"],
["foobar", 18, "f"],
["barfoo", 20, "f"]
];
I have tried this but was wondering if there was a better way of doing it.
Array.prototype.getValues = function () {
if(typeof(this[0]) != typeof({}))
throw "Array values are expected to be == typeof({})";
var items = [];
for (var i = 0; i < this.length; i++) {
var r = [];
for (var l in this[i]) {
r.push(this[i][l]);
}
items.push(r);
}
return items;
};
var newitems=[];
//loop through each item in the original
for(var i =0; i<items.length; i++)
{
newitems[i] = [];
//loop over the properties in each element and push it to an array
for(var prop in items[i]){
newitems.push(items[i][prop]);
}
}
or alternatively:
var newitems = items.map(function(elem){
var item = [];
for(var prop in elem){
item.push(elem[prop]);
}
return item;
})

Categories

Resources