Get rid of an array in javascript - javascript

There is an array for each id key that is not needed. That is kind of a group break.
const header = [
[
{ id: "1",
text: "A",
},
],
[
{ id: "2",
text: "B",
array:[1,2,3],
},
{ id: "2",
text: "B1",
},
],
[
{ id: "3",
text: "A",
},
],
];
The result should be that below. The array between the same id should disapear. Only one array that contains the data as objects should remain.
const header = [
{ id: "1",
text: "A",
},
{ id: "2",
text: "B",
array:[1,2,3],
},
{ id: "2",
text: "B1",
},
{ id: "3",
text: "A",
},
];

What you're trying to archive is called flatten.
JavaScript has the build in method to archive this: Array.prototype.flat().
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat
Example (taken from the source above)
const arr1 = [0, 1, 2, [3, 4]];
console.log(arr1.flat());
// expected output: [0, 1, 2, 3, 4]
const arr2 = [0, 1, 2, [[[3, 4]]]];
console.log(arr2.flat(2));
// expected output: [0, 1, 2, [3, 4]]

You might have to use nested loops, since every index of an array is also an array and push items in an new array.
const header = [
[{ id: '1', text: 'A' }],
[
{ id: '2', text: 'B', array: [1, 2, 3] },
{ id: '2', text: 'B1' },
],
[{ id: '3', text: 'A' }],
];
const newHeader = [];
header.forEach(headerItems => {
headerItems.forEach(headerItem => {
newHeader.push(headerItem)
});
})
console.log(newHeader);

You can using flat() method.
This link is related about flat method : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat
This is my code :
// before
const header = [
[{ id: '1', text: 'A' }],
[
{ id: '2', text: 'B', array: [1, 2, 3] },
{ id: '2', text: 'B1' }
],
[{ id: '3', text: 'A' }]
]
// expected output
const headerFlat = [
{ id: '1', text: 'A' },
{ id: '2', text: 'B', array: [1, 2, 3] },
{ id: '2', text: 'B1' },
{ id: '3', text: 'A' }
]
// using flat()
const flat = header.flat()
console.log(flat)

Related

how to create from object and nested objects one array

I have this array of objects with nested objects "children".. the number of nested children arrays that can be is not defined
let a = [
{ id: 0, title: 'a', children: [ { id: 1, title: 'aa', children: [ { id: 2, title: 'aaa', children: []} ]}] },
{ id: 3, title: 'b', children: [ { id: 4, title: 'bb', children: []}] },
{ id: 5, title: 'c', children: [] },
{ id: 6, title: 'd', children: [ { id: 7, title: 'dd', children: [ { id: 8, title: 'ddd', children: []} ]}] },
]
and I need foreach them, take to the array.. with level of nested:
let b = [
{ id: 0, title: 'a', level: 0 },
{ id: 1, title: 'aa', level: 1 },
{ id: 2, title: 'aaa', level: 2 },
{ id: 3, title: 'b', level: 0 },
{ id: 4, title: 'bb', level: 1 },
{ id: 5, title: 'c', level: 0 },
{ id: 6, title: 'd', level: 0 },
{ id: 7, title: 'dd', level: 1 },
{ id: 8, title: 'ddd', level: 2 },
]
I tired recursively code, but its not working.. thank for help
Here is a recursive function called makeLevels that outputs your result.
let a = [
{ id: 0, title: 'a', children: [{ id: 1, title: 'aa', children: [{ id: 2, title: 'aaa', children: [] }] }] },
{ id: 3, title: 'b', children: [{ id: 4, title: 'bb', children: [] }] },
{ id: 5, title: 'c', children: [] },
{ id: 6, title: 'd', children: [{ id: 7, title: 'dd', children: [{ id: 8, title: 'ddd', children: [] }] }] },
];
function makeLevels(entry, result = [], level = 0) {
for (let i = 0, len = entry.length; i < len; i++) {
const item = entry[i];
result.push({ id: item.id, title: item.title, level });
if (item.children?.length) {
makeLevels(item.children, result, level + 1);
}
}
return result;
}
console.log(makeLevels(a));
Output:
[
{ "id": 0, "title": "a", "level": 0 },
{ "id": 1, "title": "aa", "level": 1 },
{ "id": 2, "title": "aaa", "level": 2 },
{ "id": 3, "title": "b", "level": 0 },
{ "id": 4, "title": "bb", "level": 1 },
{ "id": 5, "title": "c", "level": 0 },
{ "id": 6, "title": "d", "level": 0 },
{ "id": 7, "title": "dd", "level": 1 },
{ "id": 8, "title": "ddd", "level": 2 }
]
You can try this approach:
let a = [{ id: 0, title: 'a', children: [ { id: 1, title: 'aa', children: [ { id: 2, title: 'aaa', children: []} ]}] }, { id: 3, title: 'b', children: [ { id: 4, title: 'bb', children: []}] }, { id: 5, title: 'c', children: [] }, { id: 6, title: 'd', children: [ { id: 7, title: 'dd', children: [ { id: 8, title: 'ddd', children: []} ]}] },]
function flattenArray(arr, index = 0) {
return arr.reduce((acc, {children, ...rest}) => [
...acc,
{...rest, level: index},
...flattenArray(children, index+1)
],
[])
}
console.log(flattenArray(a))
To make it a little more readable, you could also do it like this.
let a = [{ id: 0, title: 'a', children: [ { id: 1, title: 'aa', children: [ { id: 2, title: 'aaa', children: []} ]}] }, { id: 3, title: 'b', children: [ { id: 4, title: 'bb', children: []}] }, { id: 5, title: 'c', children: [] }, { id: 6, title: 'd', children: [ { id: 7, title: 'dd', children: [ { id: 8, title: 'ddd', children: []} ]}] },]
function levels(obj, level = 0, arr = []) {
for (const { id, title, children } of obj) {
arr.push({ id, title, level });
if (Array.isArray(children)) levels(children, level + 1, arr);
}
return arr;
}
console.log(levels(a))

How to filter array key by another array number key

I have 2 array, first array structure is:
items: [
{
name: "a",
items: [
{ name: "jack" },
{ name: "jose" },
]
},
{
name: "b",
items: [
{ name: "lara" },
{ name: "jo" },
]
},
{
name: "c",
items: [
{ name: "andy" },
{ name: "hary" },
]
}
]
and the second array:
number: [
0: [0, 1],
1: [1],
2: [0]
]
How to filter "items" by "number" and How can such an output be obtained? (the best solution)
{["jack", "jole"],["jo"],["andy"]}
A few maps would do it:
the output you wish is not valid JS so I made a nested array
const arr1 = [{ name: "a", items: [{ name: "jack" }, { name: "jose" }, ] }, { name: "b", items: [{ name: "lara" }, { name: "jo" }, ] }, { name: "c", items: [{ name: "andy" }, { name: "hary" }, ] } ], numbers = [ [0, 1], [1], [0] ];
const res = numbers
.map((arr, i) => arr
.map(key => arr1[i].items[key].name)
)
console.log(res)
If your number variable has to be an Object.
let items = [
{
name: "a",
items: [{ name: "jack" }, { name: "jose" }]
},
{
name: "b",
items: [{ name: "lara" }, { name: "jo" }]
},
{
name: "c",
items: [{ name: "andy" }, { name: "hary" }]
}
];
let number = {
0: [0, 1],
1: [1],
2: [0]
};
let result = []
for (const [key, value] of Object.entries(number)){
let names = []
value.forEach(value => {
names.push(items[key].items[value].name)
})
result.push(names)
}
console.log(result)

how to find distinct object from two array javascript

I have tow arrays of object like this :
const array1 = [
{ id: 1, name: 'A' },
{ id: 2, name: 'B' },
{ id: 3, name: 'C' }
]
const array2 = [
{ id: 1, name: 'A' },
{ id: 2, name: 'B' }
]
I want another array from arry1 which contains those objects which are not in array2. like this :
[{ id: 1, name: 'C' }]
I tried this approach : var finalArray = array1.filter(function (obj) { return array2.indexOf(obj) === -1; });
But its not working. Please help me
try this :
const array1 = [
{ id: 1, name: 'A' },
{ id: 2, name: 'B' },
{ id: 3, name: 'C' }
]
const array2 = [
{ id: 1, name: 'A' },
{ id: 2, name: 'B' }
]
const array2Names = array2.map(e => e.name)
const arrayYouWant = array1.filter(e => array2Names.includes(e.name) === false)
The array2Names variable return an array like this : ['A','B']
The includes method allows us to know if the analyzed array contains the element in parentheses.
We can use Array.filter and Array.find to get all the objects in array1, but not in array2.
We use .filter to find all the items in array1 that are not present in array2, using .find.
const array1 = [
{ id: 1, name: 'A' },
{ id: 2, name: 'B' },
{ id: 3, name: 'C' }
]
const array2 = [
{ id: 1, name: 'A' },
{ id: 2, name: 'B' }
]
const diff = array1.filter(x1 => !array2.find(x2 => {
return x1.id === x2.id && x1.name === x2.name;
}));
console.log(diff);
const array1 = [
{ id: 1, name: 'A' },
{ id: 2, name: 'B' },
{ id: 3, name: 'C' }
]
const array2 = [
{ id: 1, name: 'A' },
{ id: 2, name: 'B' }
]
const arr = [... new Set(array1.filter(el => !array2.some(el2 => el2.id == el.id)))];
console.log(arr);

Which is the best way to get an array difference from an object?

I have an array of values: ["1", "2", "3"] which contains essentially the reference of the records stored in this array of object:
[
{ id: 1, name: "John" },
{ id: 2, name: "Patrick" },
{ id: 3, name: "Jack" },
{ id: 4, name: "Paula" },
{ id: 5, name: "Sarah" }
]
I would like to return the missing reference from the array of objects, so the result will be: 4, 5. What I achieved so far is takes all the selected values of the first array from all the select available in the html:
var selected_options = $('.options-picker')
.map(function() { return this.value}).get();
this will return 1, 2, 3. How can I extract from the array of objects 4, 5?
Thanks in advance.
Use filter and includes to check the object ids against the values in the array.
const data = [
{ id: 1, name: "John" },
{ id: 2, name: "Patrick" },
{ id: 3, name: "Jack" },
{ id: 4, name: "Paula" },
{ id: 5, name: "Sarah" }
];
const items = [1, 2, 3];
const out = data.filter(obj => !items.includes(obj.id));
console.log(out);
This will do
var a=[
{ id: 1, name: "John" },
{ id: 2, name: "Patrick" },
{ id: 3, name: "Jack" },
{ id: 4, name: "Paula" },
{ id: 5, name: "Sarah" }
]
var b=['1', '2', '3'];
a.forEach((e)=>{
if(b.indexOf(e.id.toString())==-1)
{
b.push(e.id);
}
})
alert(b)

Get string values from array in object that is in an array

I have the following JSON object:
var test = {
data: [{
itemID: 0,
categories: [{
id: 0,
type: 'a',
name: 'world'
}, {
id: 1,
type: 'b',
name: 'plants'
}]
},
{
itemID: 1,
categories: [{
id: 2,
type: 'w',
name: 'cars'
}, {
id: 3,
type: 't',
name: 'bicycles'
}]
}
]
};
console.log([].concat
.apply([], test.data.map(item => item.categories.map(el => el.type))));
What I want to do is, to get all types in an array.
So the result should look like this:
['a', 'b', 'w', 't']
What I did:
[].concat
.apply([], test.data.map(item => item.categories.map(el => el.type)))
I have the feeling that this could be done easier.
Does someone know a better solution ?
You can use Array.prototype.map() and Array.prototype.flat():
The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
Where depth is Optional
The depth level specifying how deep a nested array structure should be flattened. Defaults to 1.
var test = {
data: [{
itemID: 0,
categories: [{
id: 0,
type: 'a',
name: 'world'
}, {
id: 1,
type: 'b',
name: 'plants'
}]
},
{
itemID: 1,
categories: [{
id: 2,
type: 'w',
name: 'cars'
}, {
id: 3,
type: 't',
name: 'bicycles'
}]
}
]
};
var type = test.data.map(item => item.categories.map(el => el.type)).flat();
console.log(type);
Use Array.reduce
var test = {data: [{itemID: 0,categories: [{id: 0,type: 'a',name: 'world'}, {id: 1,type: 'b',name: 'plants'}]},{itemID: 1,categories: [{id: 2,type: 'w',name: 'cars'}, {id: 3,type: 't',name: 'bicycles'}]}]};
let result = test.data.reduce((a,c) => a.concat(c.categories.map(v => v.type)), []);
console.log(result);

Categories