Related
I have an array, which contains array of objects. I need to extract the property value "id" of items that have objects.
Example of array:
let myArray = [
[ {id: "1"}, {id: "2"} ],
[],
[],
[ {id: "3"} ]
]
How can I extract and create an array like this:
["1", "2", "3"]
I tried this:
tagIds = myArray.map(id =>{id})
You can use reduce to flatten the array and use map to loop thru the array and return the id.
let myArray = [
[{id: "1"}, {id: "2"}],
[],
[],
[{id: "3"}],
];
let result = myArray.reduce((c, v) => c.concat(v), []).map(o => o.id);
console.log(result);
Another way with simple nested loops:
let myArray = [
[ {id: "1"}, {id: "2"} ],
[],
[],
[ {id: "3"} ]
]
//----------------------------------
let newArray=[];
for (let i=0;i<myArray.length;i++){
for (let j=0;j<myArray[i].length;j++){
newArray.push(myArray[i][j].id);
}
}
console.log(newArray); //outputs ['1','2','3']
You can use .concat() to create array of single objects and then .map() to extract ids:
let myArray = [
[{id: "1"}, {id: "2"}], [], [], [{id:"3"}]
];
let result = [].concat(...myArray).map(({ id }) => id);
console.log(result);
Docs:
Array.prototype.concat()
Array.prototype.map()
Spread Syntax
Here is my solution:
let a = myArray.flat(100) // you can put (3) or (10) in here, the higher the flatter the array
let b = a.map(
function(value){
return parseInt(value.id)
}
)
console.log(b)
You can also write a recursive function to make this work with any number of arrays, for example:
function extractIds(arr) {
return arr.reduce((a, item) => {
if (Array.isArray(item)) {
return [
...a,
...extractIds(item)
];
}
return [
...a,
item.id
];
}, [])
}
extractIds([{id: 1}, [{id: 2}], {id: 3}, [{id: 4}, [{id: 5}, [{id: 6}]]]])
the return of extractIds will be [1, 2, 3, 4, 5, 6].
Notice that without the recursive part you would end up with something like this: [1, 2, [3, {id: 4}, [{id: 5}]]] (Not exactly like this, but just as an example).
I have two arrays
let arr1 = [{'id': 'ee', 'seat': '12'},
{'id': 'aa', 'seat': '8'}
]
let arr2 = [
{'id': 's22', 'num': ''},
{'id': '2s2', 'num': ''}
]
I want to copy seat values from arr1 to num property at arr2, but I only get last arr1 seat value in for loop.
for( let i = 0; i <= arr1.length; i++) {
for( let x = 0; x <= arr2.length; x++) {
arr2[x]['num'] = arr1[i]['seat'];
}
}
console.log(arr2);
Iterate arr2 with Array.forEach(), and take the respective seat value by index from arr1:
const arr1 = [{'id': 'ee', 'seat': '12'},{'id': 'aa', 'seat': '8'}]
const arr2 = [{'id': 's22', 'num': ''},{'id': '2s2', 'num': ''}]
arr2.forEach((o, i) => o.num = arr1[i].seat)
console.log(arr2)
You need just a single loop and check if the index of the array if is (only) smaller than the length of the minimum of both arrays.
If the index get the length of an array, the access returns undefined, because this element is not in the array.
A further access to a property of this throws an error:
Unable to get property 'seat' of undefined or null reference
var arr1 = [{ id: 'ee', seat: '12' }, { id: 'aa', seat: '8' }],
arr2 = [{ id: 's22', num: '' }, { id: '2s2', num: '' }],
i, l;
for (i = 0, l = Math.min(arr1.length, arr2.length); i < l; i++) {
arr2[i].num = arr1[i].seat;
}
console.log(arr2);
You can do it in just one for loop.
for(let i = 0; i < arr1.length; i++) {
arr2[i].num = arr1[i].seat;
}
Hope this helps!
Assuming you want to match indices, this should do it.
const arr1 = [
{'id': 'ee', 'seat': '12'},
{'id': 'aa', 'seat': '8'}
]
const arr2 = [
{'id': 's22', 'num': ''},
{'id': '2s2', 'num': ''}
]
const result = arr2.map((e, i) => ({...e, ...{num: arr1[i].seat}}))
console.log(result)
If you want all of the seats in each num, it wouldn't be much harder.
I have two arrays.
array1 = [
{'id':1},
{'id': 2}
]
and
array2 = [
{'idVal':1},
{'idVal': 2},
{'idVal': 3},
{'idVal': 4}
]
I need a optimal way, lodash if possible so that i can compare these two arrays and get a result array that has object present in array2 and not in array1. The keys have different name in both arrays. So the result will be,
res = [
{'idVal': 3},
{'idVal': 4}
]
Use _.differenceWith() with a comparator method. According to the docs about _.difference() (differenceWith is based on difference):
Creates an array of array values not included in the other given
arrays using SameValueZero for equality comparisons. The order and
references of result values are determined by the first array.
So array2 should be the 1st param passed to the method.
var array1 = [
{'id': 1},
{'id': 2}
];
var array2 = [
{'idVal': 1},
{'idVal': 2},
{'idVal': 3},
{'idVal': 4}
];
var result = _.differenceWith(array2, array1, function(arrVal, othVal) {
return arrVal.idVal === othVal.id;
});
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Using ES6
const result = array2.filter(item => !array1.find(i => i.idVal === item.id))
var array1 = [
{'id':1},
{'id': 2},
{'id': 3},
{'id': 4}
]
var array2 = [
{'id':1},
{'id': 3},
{'id': 4}
]
notInArray2 = array1.reduce( function(acc, v) {
if(!array2.find(function (vInner) {
return v.id === vInner.id;
})){
acc.push(v);
}
return acc
}, []);
console.log(JSON.stringify(notInArray2))
Here's an optimized solution, not using lodash though. I created a search index containing just the values of array1, so that you can look up elements in O(1), rather than going through the entire array1 for every element in array2.
Let m be the size of array1 and n be the size of array2. This solution will run in O(m+n), as opposed to O(m*n) that you would have without prior indexing.
const array1 = [
{'id':1},
{'id': 2}
];
const array2 = [
{'idVal':1},
{'idVal': 2},
{'idVal': 3},
{'idVal': 4}
];
const array1ValuesIndex = {};
array1.forEach(entry => array1ValuesIndex[entry.id] = true);
const result = array2.filter(entry => !array1ValuesIndex[entry.idVal]);
console.log(result);
array1 = [
{'id':1},
{'id': 2}
]
array2 = [
{'idVal':1},
{'idVal': 2},
{'idVal': 3},
{'idVal': 4}
]
var array1Keys=array1.map(function(d1){ return d1.id});
var result =array2.filter(function(d){ return array1Keys.indexOf(d.idVal)==-1 })
console.log(result);
a = [
{ id: 1, books: [1, 2, 3, 4] },
{ id: 2, books: [1, 2, 3] },
{ id: 3, books: [1, 2, 3, 4, 5] },
{ id: 9, books: [1, 2] }
];
b = [{ id: 2, books: [1, 2, 3] }, { id: 3, books: [1, 2, 3, 4, 5] }];
I want to delete array b the same id elements from a.
How to do that? Thanks.
It means:
I want to get the a = [{id: 1, books: [1,2,3,4]}], get rid the same element within array b;
my code is:
const delDuplicate = (a, b) => {
const bLen = b.length;
if (!bLen) return a;
for (let i = 0; i < a.length; i++) {
for (let j = 0; j < bLen; j++) {
if (a[i].id === b[j].id) {
const delItem = a.splice(i, 1)[0];
console.log(delItem);
}
}
}
return a;
};
a = delDuplicate(a, b);
It works, is there a better way? I think reduce and map maybe work too.
These two arrays are not simple array. So can not use a.indexOf(b[i]) !== -1.
You can use .map(), .reduce(), .filter(), .indexOf()
var ids = b.map(o => o.id);
a = a.reduce((res, o) =>
[...res] = [...res.filter(Boolean), ids.indexOf(o.id) < 0 && o], []);
var a = [{id: 1, books: [1,2,3,4]}, {id: 2, books: [1,2,3]}, {id: 3, books: [1,2,3,4,5]}, {id: 9, books: [1,2]}];
var b = [{id: 2, books: [1,2,3]}, {id: 3, books: [1,2,3,4,5]}];
var ids = b.map(o => o.id);
a = a.reduce((res, o) =>
[...res] = [...res.filter(Boolean), ids.indexOf(o.id) < 0 && o], []);
console.log(a);
I found another way to do this. By looping through both arrays and if a match/duplicate is NOT found add this element to a third array. The third array can over write the A array at the end if required. Have tested and works.
var a = [{id: 1, books: [1,2,3,4]}, {id: 2, books: [1,2,3]}, {id: 3, books: [1,2,3,4,5]}, {id: 9, books: [1,2]}];
var b = [{id: 2, books: [1,2,3]}, {id: 3, books: [1,2,3,4,5]}];
var c = []; // New array to sort parsed A array
var boolMatch; // Boolean if duplicate is found
for(i = 0; i < a.length; i++){
boolMatch = false; // Required to reset the Boolean at the start of each loop
for(j = 0; j < b.length; j++){
if(a[i].id == b[j].id){
boolMatch = true;
break;
}
}
if(!boolMatch) c.push(a[i]); // Add to C array if element from A is NOT found in B array
}
Firstly: your question is a bit unclear to me. If you clarify, I can make this answer better. I'm asuming that you are trying to remove elements from b that have same value as the corresponding element in array a. I'm also assuming that you want to update the incidences during the search.
Now IDK the exact syntax of Javascript, so this may be a bit off. However, it should give you a general idea of what to do. (I'll try and fix the code after I research a bit)
a = [{id: 1, books: [1,2,3,4]}, {id: 2, books: [1,2,3]}, {id: 3, books: [1,2,3,4,5]}, {id: 9, books: [1,2]}]
b = [{id: 2, books: [1,2,3]}, {id: 3, books: [1,2,3,4,5]}]
//set loop size to size of the smaller array
var lsize=b.length;
if(a.length<b.length) lsize = a.length;
//loop through length
for(var i = 0; i < lsize; i++) {
if(a[i] != b[i]) { //check if the values of the elements are the same
b.splice(i, 1); //remove the element from b
i=-1; //reset loop to check rest of elements
lsize-=1; //reduce size since there is one less
}
}
To make sure you compare all the elements correctly, you should sort them by the ids to make sure you're comparing the right array elements together. This solution assumes the objects only have one other property to compare, books, which is a sorted array.
// initialize arrays
var a = [{id: 1, books: [1,2,3,4]}, {id: 2, books: [1,2,3]}, {id: 3, books: [1,2,3,4,5]}, {id: 9, books: [1,2]}];
var b = [{id: 2, books: [1,2,3]}, {id: 3, books: [1,2,3,4,5]}];
// comparator
var comp = function(a,b) {
return a.id-b.id;
};
// index for array a
var j = 0;
// sort arrays
a.sort(comp);
b.sort(comp);
// check all elements in b against those with matching ids in a
for(var i=0; i<b.length; i++) {
// find next matching id in a
while(a[j].id<b[i]&&j<a.length) {
j++;
}
// break if no more elements to check against in a
if(j==a.length) {
break;
}
// compare elements with matching ids to see if the books array make the same string
// comparing array references won't work, so they're converted to strings instead
if(a[j].id==b[i].id&&a[j].books.join(",")==b[i].books.join(",")) {
// remove element from b and don't skip over next element
b.splice(i,1);
i--;
}
}
// b should share no elements with a
I have a stupid problem that at first seems to be simple to solve, but turns out to be tricky.
I have an array of objects, each with two properties: id and value:
[
{id: 2, value: 10},
{id: 4, value: 3},
{id: 2, value: 2},
{id: 1, value: 15}
]
I want to write an algorithm that sums up the values of ones with similar id.
My end result should be a new array with only the merged objects:
[
{id: 2, value: 12},
{id: 4, value: 3},
{id: 1, value: 15}
]
I've tried the following, but it doesn't work:
var arr = [];
arr.push({id: 2, visit:10});
arr.push({id: 4, visit:3});
arr.push({id: 2, visit:2});
arr.push({id: 1, visit:15});
// Deep copy
var copy = jQuery.extend(true, [], arr);
var masterArr = [];
for (var i = 0; i < arr.length; i++) {
var objArr = [];
objArr.push(arr[i]);
for (var j = copy.length-1; j > -1; j--) {
if (arr[i].id === copy[j].id) {
var q = copy.splice(j,1);
}
}
masterArr.push(objArr);
}
My plan was to first gather all similar objects in separate arrays (objArr), sum them up and put them in an end array (masterArr). I use jquerys extend to make a deep copy (not a reference) and reverse iteration and splice to remove objects thats already been found as "duplicates".
This doesn't work! And it doesn't seem to be a very efficient mehtod to solve my problem.
How could I do this? Performance isn't top priority but rather "nice to have"!
Thanks!
You can do it like this:
// Assuming:
a = [{id: 2, value: 10}, {id: 4, value: 3}, {id: 2, value: 2}, {id: 1, value: 15}]
var b = {}, // Temporary variable;
c = []; // This will contain the result;
// Build a id:value object ( {1: 15, 2: 12, 4: 3} )
a.map(function(current){b[current.id] = (b[current.id] || 0) + current.value});
for(var key in b){ // Form that into the desired output format.
c.push({id: parseInt(key, 10), value: b[key]});
}
console.log(c);
/* [{id: 1, value: 15},
{id: 2, value: 12},
{id: 4, value: 3}] */
I'm using parseInt(key, 10), since the keys are strings, you'll probably want them converted to integers again.
// First group the data based on id and sum the values
var temp = data.reduce(function(result, current) {
result[current.id] = (result[current.id] || 0) + current.value;
return result;
}, {});
// then recreate the objects with proper id and value properties
var result = [];
for (var key in temp) {
result.push({
id: parseInt(key, 10),
value: temp[key]
});
}
console.log(result);
Output
[ { id: 1, value: 15 },
{ id: 2, value: 12 },
{ id: 4, value: 3 } ]
The quickest approach loops over the array only once using Array.prototype.filter():
var tmp = {},
result = arr.filter(function (el) {
if (tmp.hasOwnProperty(el.id)) {
tmp[el.id].visit += el.visit;
return false;
}
else {
tmp[el.id] = el;
return true;
}
});
It also reuses the objects, though this renders the original array to contain inaccurate values. If this is a problem, you can modify the example to copy each object property to a new object.