Consider the following function's blueprint which tries to compare two objects:
function objectCompare(a,b,path){
for (var prop in a) {
path=prop;
if (a.hasOwnProperty(prop) && !(b.hasOwnProperty(prop))) {
...
return false;
}
...
if (detectType(a[prop])==='Object'){
if (!objectCompare(a[prop],b[prop],path))
return false;
}
...
}
return true;
}
detectType is my own function which checks the type of a variable. My problem is that I want to enrich variable path every time we have a recursive call. However, at the same time when recursive calls finish, path has to traverse the remaining property names of the initial object without being enriched...
Imagine the following objects:
var Obj1 = {
p1: 's',
p2: {
p1: {a: { propA: 'a', propB: 'b' }},
p2: 'g',
}
};
var Obj2 = {
p1: 's',
p2: {
p1: {a: { propA: 'a', propB: 'c' }},
p2: 'g',
}
};
I want path when function objectComparereturns to have the following value: p2.p1.a.propB Namely, the point which makes the two objects different. How may I achieve that?
You have to add the current key to the path and pass the new path to the recursive call. Consider:
console.info=function(x){document.write('<pre>'+JSON.stringify(x,0,3)+'</pre>')}
//--
// compare: return path if a,b are different, null otherwise
function compare(a, b, path) {
var ta = typeof a,
tb = typeof b;
// different types - fail
if (ta !== tb) {
return path;
}
// scalars - null if equal, path if not
if (ta !== 'object') {
return a === b ? null : path;
}
// make a set of keys from both objects
var keys = Object.keys(a).concat(Object.keys(b)).filter(function(x, i, self) {
return self.indexOf(x) === i;
});
// for each key in set, compare values
var res = null;
keys.some(function(k) {
return res = compare(a[k], b[k], path.concat(k));
});
// return null or the first failed path
return res;
}
//
var Obj1 = {
p1: 's',
p2: {
p1: {a: { propA: 'a', propB: 'b' }},
p2: 'g',
}
};
var Obj2 = {
p1: 's',
p2: {
p1: {a: { propA: 'a', propB: 'c' }},
p2: 'g',
}
};
var res = compare(Obj1, Obj2, [])
console.info(res);
The library deep-diff does what you need.
The above reference presents this example code:
var diff = require('deep-diff').diff;
var lhs = {
name: 'my object',
description: 'it\'s an object!',
details: {
it: 'has',
an: 'array',
with: ['a', 'few', 'elements']
}
};
var rhs = {
name: 'updated object',
description: 'it\'s an object!',
details: {
it: 'has',
an: 'array',
with: ['a', 'few', 'more', 'elements', { than: 'before' }]
}
};
var differences = diff(lhs, rhs);
The code snippet above would result in the following structure describing the differences:
[ { kind: 'E',
path: [ 'name' ],
lhs: 'my object',
rhs: 'updated object' },
{ kind: 'E',
path: [ 'details', 'with', 2 ],
lhs: 'elements',
rhs: 'more' },
{ kind: 'A',
path: [ 'details', 'with' ],
index: 3,
item: { kind: 'N', rhs: 'elements' } },
{ kind: 'A',
path: [ 'details', 'with' ],
index: 4,
item: { kind: 'N', rhs: { than: 'before' } } } ]
Notably the path property is much like your desired output.
Related
interface FormValues {
key: string;
value: any;
}
const array: FormValues[] = [
{
key: 'A',
value: 1 // number
},
{
key: 'A',
value: 1 // number
},
{
key: 'A',
value: 'str' // string
},
{
key: 'C',
value: { a: 1, b: '2' } // object
},
{
key: 'C',
value: ['a','2'] // array
},
{
key: 'C',
value: ['a','2'] // array
}
{
key: 'B',
value: true // boolean
}
]
I want to filter the objects based on field value, which can have a value of any type.
I tried to do it like this; my solution is not working for nested object checks.
const key = 'value';
const arrayUniqueByKey = [...new Map(array.map(item => [item[key], item])).values()];
output :
[{
key: 'A',
value: 1 // number
},
{
key: 'A',
value: 'str' // string
},
{
key: 'C',
value: { a: 1, b: '2' } // object
},
{
key: 'C',
value: ['a','2'] // array
},
{
key: 'B',
value: true // boolean
}]
You need to decide what makes two distinct objects "equal". In JavaScript, all built-in comparisons of objects (which includes arrays) are by reference. That means ['a','2'] === ['a','2'] is false because two distinct array objects exist, despite having the same contents. See How to determine equality for two JavaScript objects? for more information.
I will take the approach that you would like two values to be considered equal if they serialize to the same value via a modified version of JSON.stringify() where the order of property keys are guaranteed to be the same (so {a: 1, b: 2} and {b: 2, a: 1} will be equal no matter how those are stringified). I use a version from this answer to do so:
function JSONstringifyOrder(obj: any, space?: number) {
var allKeys: string[] = [];
var seen: Record<string, null | undefined> = {};
JSON.stringify(obj, function (key, value) {
if (!(key in seen)) {
allKeys.push(key); seen[key] = null;
}
return value;
});
allKeys.sort();
return JSON.stringify(obj, allKeys, space);
}
And now I can use that to make the keys of your Map:
const arrayUniqueByKey = [...new Map(array.map(
item => [JSONstringifyOrder(item[key]), item]
)).values()];
And you can verify that it behaves as you'd like:
console.log(arrayUniqueByKey);
/* [{
"key": "A",
"value": 1
}, {
"key": "A",
"value": "str"
}, {
"key": "C",
"value": {
"a": 1,
"b": "2"
}
}, {
"key": "C",
"value": [
"a",
"2"
]
}, {
"key": "B",
"value": true
}] */
Playground link to code
This will combine any duplicate keys, creating a new property values to hold the array of combined values (from like keys).
const array = [{key: 'A', value: 1},{key: 'A', value: 'str'},{key: 'C', value: { a: 1, b: '2'}},{key: 'B',value: true}]
const arrayUniqueByKey = [array.reduce((b, a) => {
let f = b.findIndex(c => c.key === a.key)
if (f === -1) return [...b, a];
else {
b[f].values = [...[b[f].value], a.value];
return b
}
}, [])];
console.log(arrayUniqueByKey)
You can use Array.prototype.reduce() combined with JSON.stringify() and finaly get the result array of values with Object.values()
const array = [{key: 'A',value: 1,},{key: 'A',value: 1,},{key: 'A',value: 'str',},{key: 'C',value: { a: 1, b: '2' },},{key: 'C',value: ['a', '2'],},{key: 'C',value: ['a', '2'],},{key: 'B',value: true}]
const result = Object.values(array.reduce((a, c) => ((a[JSON.stringify(c)] = c), a), {}))
console.log(result)
for example I have an object that that has objects and arrays in itself:
const object =
{
a: {
b: [
0: 'something',
1: {
c: 'the thing that I need',
},
],
},
};
and an array that has the keys as values:
const array =
[
'a', 'b', '1', 'c',
];
How can I use this array to navigate in the object and give me the value?
Maybe there is a way to do this with ramda? or just in general to make it look human readable.
You can reduce the array defining the path through the object.
You do have an error in the array. The path should be: [ 'a', 'b', '1', 'c' ], because the thing you need is inside the second element of the b array, not the first.
const object = {
a: {
b: [
'something',
{ c: 'the thing that I need' }
],
},
};
const path = [ 'a', 'b', '1', 'c' ];
const result = path.reduce(( source, next ) => source[ next ], object );
console.log( result );
Ian Hoffman-Hicks' superb crocks library has a function that does exactly that
import propPathOr from 'crocks/helpers/propPathOr'
const getC = propPathOr(null, ['a', 'b', '0', 'c'])
getC({ a: { b: [{ c: 'gotcha!' }] } }) === 'gotcha!' // true
This function is called path in Ramda.
i know there has many answer for unique array
but they can't handle with array of array
what i want is
source array
[
1,
0,
true,
undefined,
null,
false,
['a', 'b', 'c'],
['a', 'b', 'c'],
['a', 'c', 'b'],
{ a: { b: 2 } },
{ a: { b: 2 } },
{ a: { b: 3 } },
{ a: { b: undefined } },
{ a: { } },
{ a: { b: 3, c: undefined } },
]
the return
[
1,
0,
true,
undefined,
null,
false,
['a', 'b', 'c'],
['a', 'c', 'b'],
{ a: { b: 2 } },
{ a: { b: 3 } },
{ a: { b: undefined } },
{ a: { } },
{ a: { b: 3, c: undefined } },
]
arr-unique can handle object[], but can't handle array of array
Set can't too
fail code
console.log(array_unique(data));
console.log([...new Set(data)]);
console.log(data.filter(function (el, index, arr)
{
return index == arr.indexOf(el);
}));
===================
update
i create a module for this array-hyper-unique, but didn't use json stringify because it has a bug when valuse is regexp
One easy method would be to stringify the arrays and objects in order to identify duplicates:
const input = [
1,
true,
['a', 'b', 'c'],
['a', 'b', 'c'],
{ a: { b: 2 } },
{ a: { b: 2 } },
{ a: { b: 3 } },
{ a: { b: 3, c: undefined } },
];
const outputSet = new Set();
const stringifiedObjs = new Set();
input.forEach(item => {
if (typeof item !== 'object') outputSet.add(item);
else {
// replace undefineds with something, else they'll be ignored by JSON.stringify:
const stringified = JSON.stringify(
item,
(k, v) => v === undefined ? 'undefined-value' : v
);
if (!stringifiedObjs.has(stringified)) {
outputSet.add(item);
stringifiedObjs.add(stringified)
}
}
});
console.log([...outputSet]);
Try by converting elements to string using JSON.stringify and use indexOf to push these elements to another array,only if the another array does not contain this element. Then again use map & JSON.parse to convert string to the original format
var data = [
1,
true, ['a', 'b', 'c'],
['a', 'b', 'c'],
{
a: {
b: 2
}
},
{
a: {
b: 2
}
},
{
a: {
b: 3
}
},
]
// Create a new array of only string
// map will give new array and JSON.stringify will convert elements to string
var newData = data.map(function(item) {
return JSON.stringify(item)
})
//An empty array which will contain only unique values
var uniques = [];
// loop over the array of stirngs and check
//if that value is present in uniques array
//if not then push the element
newData.forEach(function(item) {
if (uniques.indexOf(item) === -1) {
uniques.push(item)
}
});
//Convert array of string to json
var parsedArr = uniques.map(function(item) {
return JSON.parse(item)
});
console.log(parsedArr)
The reason you method does not work, is because the first ['a', 'b', 'c'], and the second ['a', 'b', 'c'] are different objects, as are the first and second instances of { a: { b: 2 } }.
Because of this, even though you add them to Set, they will be considered non-equivalent to each other, and therefore, not be filtered for uniqueness.
It seems you want to get a unique array based on the absolute values in each object. One easy way to do this is to use the ES6 Map like so:
function uniq(arr) {
var uniqMap = new Map()
arr.forEach(element => {
uniqMap.set(JSON.stringify(element), element)
})
return [...uniqMap.values()]
}
You can then get the result you are looking for:
uniq(data)
//Result: [ 1, true, [ 'a', 'b', 'c' ], { a: { b: 2 } }, { a: { b: 3 } } ]
You could take a recursive approach for objects and check the values.
function check(a, b) {
if (!a || typeof a !== 'object') {
return a === b;
}
var keys = Object.keys(a);
return keys.length === Object.keys(b).length
&& keys.every(k => k in b && check(a[k], b[k]));
}
var array = [1, 0, true, undefined, null, false, ['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'c', 'b'], { a: { b: 2 } }, { a: { b: 2 } }, { a: { b: 3 } }, { a: { b: undefined } }, { a: {} }, { a: { b: 3, c: undefined } }],
unique = array.reduce((r, b) => (r.some(a => check(a, b)) || r.push(b), r), []);
console.log(unique);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Example object array:
[{
id: 'a',
beforeId: null
}, {
id: 'b',
beforeId: 'c'
}, {
id: 'c',
beforeId: 'a'
}, {
id: 'd',
beforeId: 'b'
}]
Output order: d-b-c-a; each element sorted relative to each other element based on its beforeId property.
I could make a temporary array and sort the above array. Is sorting possible with array.sort?
You could build an object with the relations and generate the result by using the object with beforeId: null and unshift all objects for the result array.
The next object is the one with the actual val as key.
Complexity: O(2n).
function chain(array) {
var o = {}, pointer = null, result = [];
array.forEach(a => o[a.beforeId] = a);
while (o[pointer]) {
result.unshift(o[pointer]);
pointer = o[pointer].val;
}
return result;
}
var data = [{ val: 'a', beforeId: null }, { val: 'b', beforeId: 'c' }, { val: 'c', beforeId: 'a' }, { val: 'd', beforeId: 'b' }];
console.log(chain(data));
.as-console-wrapper { max-height: 100% !important; top: 0; }
This is a terribly inefficient and naïve algorithm, but it works:
const array = [
{id: 'a', beforeId: null},
{id: 'b', beforeId: 'c'},
{id: 'c', beforeId: 'a'},
{id: 'd', beforeId: 'b'}
];
// find the last element
const result = [array.find(i => i.beforeId === null)];
while (result.length < array.length) {
// find the element before the first element and prepend it
result.unshift(array.find(i => i.beforeId == result[0].id));
}
console.log(result);
Is sorting possible with array.sort?
sure, with a helper function:
graph = [
{id: 'a', beforeId: null},
{id: 'b', beforeId: 'c'},
{id: 'c', beforeId: 'a'},
{id: 'd', beforeId: 'b'}
];
let isBefore = (x, y) => {
for (let {id, beforeId} of graph) {
if (id === x)
return (beforeId === y) || isBefore(beforeId, y);
}
return false;
};
graph.sort((x, y) => x === y ? 0 : (isBefore(x.id, y.id) ? -1 : +1))
console.log(graph);
isBefore returns true if x is before y immediately or transitively.
For generic, non-linear topological sorting see https://en.wikipedia.org/wiki/Topological_sorting#Algorithms
UPD: As seen here, this turned out to be horribly inefficient, because sort involves many unnecessary comparisons. Here's the fastest (so far) version:
function sort(array) {
let o = {}, res = [], len = array.length;
for (let i = 0; i < len; i++)
o[array[i].beforeId] = array[i];
for (let i = len - 1, p = null; i >= 0; i--) {
res[i] = o[p];
p = o[p].id;
}
return res;
}
which is the #Nina's idea, optimized for speed.
You may try this approach :
// order(null, vals, []) = ["d", "b", "c", "a"]
function order(beforeId, vals, result){
var id = beforeId || null;
var before = vals.filter(function(val){
return val.beforeId === id
});
if (before.length === 0) return result;
return order(before[0].val,
vals,
[before[0].val].concat(result));
}
I am trying to find a library able to say if an object B includes all property and values of an object A (and not the opposite !).
It means 2 things that the librairies i found do not handle:
The object B could have more keys than object A, and it could be
true.
The object B could have more items in its arrays than object
A, and it could be true.
This is basically what the method _.difference() of lodash does, but only for items in arrays.
i found interesting libraries like deep-diff, but anything for my need.
I could code something doing the job, but i am convinced other peoples met this need before.
Here is an example with 2 objects:
var A = {
name: 'toto',
pets: [ { name: 'woof', kind: 'dog' } ]
};
var B = {
name: 'toto',
pets: [ { name: 'gulp', kind: 'fish' }, { name: 'woof', kind: 'dog' } ],
favoriteColor: 'blue'
};
Here, A includes B since we can find in B every properties and values of A.
But librairies like diff would say no, since this is not the first but the second item of "pets" which is equal to A, and B has an additionnal property "favoriteColor".
Do you know a librairy able to do this kind of comparison?
You could use a modified version of the deepCompare that was linked in the comments. Really you just need to get past the keys length comparison, it seems.
// where b has all of a
function deepHas(a, b) {
if (typeof a !== typeof b) {
return false;
}
if (typeof a !== 'object') {
return a === b;
}
// you may need to polyfill array higher-order functions here
if(Array.isArray(a) && Array.isArray(b)) {
return a.every(function(av) {
return b.indexOf(av) !== -1;
});
}
if (Object.keys(a).length > Object.keys(b).length) {
return false;
}
for (var k in a) {
if (!(k in b)) {
return false;
}
if (!deepHas(a[k], b[k])) {
return false;
}
}
return true;
}
var a1 = {
foo: ['a', 'b', 'c'],
bar: 'bar',
baz: {
baz: {
baz: 'wee'
}
}
};
var b1 = {
foo: ['a', 'b', 'c', 'd'],
bar: 'bar',
baz: {
baz: {
baz: 'wee',
whatever: 'wat'
}
},
ok: 'test'
};
console.log('b1 has all of a1', deepHas(a1, b1));
var a2 = {
foo: ['a', 'b', 'c'],
bar: 'bar',
baz: {
baz: {
baz: 'wee'
}
}
};
var b2 = {
foo: ['a', 'b', 'c'],
baz: {
baz: {
baz: 'wee'
}
}
};
console.log('b2 does not have all of a2', !deepHas(a2, b2));
console.log('["a","b"] has ["b"]', deepHas(["b"], ["a","b"]));
console.log('{foo: ["a","b"]} has {foo: ["b"]}', deepHas({ foo: ["b"] }, { foo:["a","b"] }));