Javascript array remove every other element - javascript

I'm looking for a way to remove array other elements.
But I don't know how to do it.
This is my array:
musics: [
{
id: 1,
cover: require('~/assets/images/cover/music/ali_zand_vakili_jadeh_shab.jpg'),
title: 'جاده شب',
artist: 'علی زند وکیلی',
source: 'http://media.mtvpersian.net/2019/Mar/21/Ali%20Zand%20Vakili%20-%20Jadeh%20Shab.mp3'
},
{
id: 2,
cover: require('~/assets/images/cover/music/amin_hayaei_divoone_misazi.jpg'),
title: 'دیوونه میسازی',
artist: 'امین حیایی',
source: 'https://cdnmrtehran.ir/media/mp3s_128/Amin_Hayaei/Singles/amin_hayaei_divoone_misazi.mp3'
},
{
id: 3,
cover: require('~/assets/images/cover/music/emad_talebzadeh_maghrour.jpg'),
title: 'مغرور',
artist: 'عماد طالب زاده',
source: 'https://cdnmrtehran.ir/media/mp3s_128/Emad_Talebzadeh/Singles/emad_talebzadeh_maghrour.mp3'
},
{
id: 4,
cover: require('~/assets/images/cover/music/farzad_farzin_jazzab.jpg'),
title: 'جذاب',
artist: 'فرزاد فرزین',
source: 'https://cdnmrtehran.ir/media/mp3s_128/Farzad_Farzin/Singles/farzad_farzin_jazzab.mp3'
},
{
id: 5,
cover: require('~/assets/images/cover/music/hamid_sefat_ajayeb_shahr_merat_remix.jpg'),
title: 'عجایب شهر رمیکس',
artist: 'حمید صفت',
source: 'https://cdnmrtehran.ir/media/mp3s_128/Hamid_Sefat/Singles/hamid_sefat_ajayeb_shahr_merat_remix.mp3'
}
],
How to remove all elements except element with id of 3 ?

To remove all the even indexed elements you could use the following:
musics = musics.filter((e, i) => i % 2 == 0)
To remove the odd ones simply change the == with !=

var musics= [{id: 1,cover: '~/assets/images/cover/music/ali_zand_vakili_jadeh_shab.jpg',title: 'جاده شب',artist: 'علی زند وکیلی',source: 'http://media.mtvpersian.net/2019/Mar/21/Ali%20Zand%20Vakili%20-%20Jadeh%20Shab.mp3'},
{id: 2,cover: '~/assets/images/cover/music/amin_hayaei_divoone_misazi.jpg',title: 'دیوونه میسازی',artist: 'امین حیایی',source: 'https://cdnmrtehran.ir/media/mp3s_128/Amin_Hayaei/Singles/amin_hayaei_divoone_misazi.mp3'},
{id: 3,cover: '~/assets/images/cover/music/emad_talebzadeh_maghrour.jpg',title: 'مغرور',artist: 'عماد طالب زاده',source: 'https://cdnmrtehran.ir/media/mp3s_128/Emad_Talebzadeh/Singles/emad_talebzadeh_maghrour.mp3'},
{id: 4,cover: '~/assets/images/cover/music/farzad_farzin_jazzab.jpg',title: 'جذاب',artist: 'فرزاد فرزین',source: 'https://cdnmrtehran.ir/media/mp3s_128/Farzad_Farzin/Singles/farzad_farzin_jazzab.mp3'},
{id: 5,cover:'~/assets/images/cover/music/hamid_sefat_ajayeb_shahr_merat_remix.jpg',title: 'عجایب شهر رمیکس',artist: 'حمید صفت',source: 'https://cdnmrtehran.ir/media/mp3s_128/Hamid_Sefat/Singles/hamid_sefat_ajayeb_shahr_merat_remix.mp3'}]
var result =[];
musics.forEach(function(item){
if(item.id == 3){
result.push(item);
}
});
console.log(result);

You can use filter: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
musics = musics.filter (x => x.id == 3)

Related

React JS - check if an array of objects includes more objects in it

Please help me. all I want is show the <div className="songs-list-header-col">Album</div> only when the tracks array includes the artist property as an object. I have some scenarios where artist is not an object there I don't want show the <div>. what should I do.
tracks [
0:{
album: {id: 1, album_name: "Fearless (Taylor's Version)"}
artist: {id: 1, artist_name: "Taylor Swift"}
genre: "POP"
id: 1
time: "00:03:49"
track_name: "Love Story"
},
1: {
album: {id: 1, album_name: "Fearless (Taylor's Version)"}
artist: {id: 1, artist_name: "Taylor Swift"}
genre: "POP"
id: 2
time: "00:03:40"
track_name: "You Belong With Me"
},
2: {
album: {id: 2, album_name: "Divide"}
artist: {id: 2, artist_name: "Ed Sheeran"}
genre: "POP"
id: 4
time: "00:04:23"
track_name: "Perfect"
}
]
I know map is not the solution but I tried it it is giving the solution but just like map works it prints the div 3 times. but all I want is that check if artist is an object or not. if it's object print div.
{
tracks.map((track) => {
return (
typeof track.artist === 'object' &&
<div className="songs-list-header-col">Album</div>
)
})
}
and also I'm not able to directly check like tracks[0].artist it gives the type error. what should I do.
You can do
tracks.filter(track => typeof track.artist === 'object')
.map(track => <div className="songs-list-header-col">Album</div>)

Create a key map for all paths in a recursive/nested object array

I have an n levels deep nested array of tag objects with title and ID. What I'm trying to create is a an object with IDs as keys and values being an array describing the title-path to that ID.
I'm no master at recursion so my attempt below doesn't exactly provide the result I need.
Here's the original nested tag array:
const tags = [
{
title: 'Wood',
id: 'dkgkeixn',
tags: [
{
title: 'Material',
id: 'ewyherer'
},
{
title: 'Construction',
id: 'cchtfyjf'
}
]
},
{
title: 'Steel',
id: 'drftgycs',
tags: [
{
title: 'Surface',
id: 'sfkstewc',
tags: [
{
title: 'Polished',
id: 'vbraurff'
},
{
title: 'Coated',
id: 'sdusfgsf'
}
]
},
{
title: 'Quality',
id: 'zsasyewe'
}
]
}
]
The output I'm trying to get is this:
{
'dkgkeixn': ['Wood'],
'ewyherer': ['Wood', 'Material'],
'cchtfyjf': ['Wood', 'Construction'],
'drftgycs': ['Steel'],
'sfkstewc': ['Steel', 'Surface'],
'vbraurff': ['Steel', 'Surface', 'Polished'],
'sdusfgsf': ['Steel', 'Surface', 'Coated'],
'zsasyewe': ['Steel', 'Quality']
}
So I'm building this recursive function which is almost doing it's job, but I keep getting the wrong paths in my flat/key map:
function flatMap(tag, acc, pathBefore) {
if (!acc[tag.id]) acc[tag.id] = [...pathBefore];
acc[tag.id].push(tag.title);
if (tag.tags) {
pathBefore.push(tag.title)
tag.tags.forEach(el => flatMap(el, acc, pathBefore))
}
return acc
}
const keyMap = flatMap({ title: 'Root', id: 'root', tags}, {}, []);
console.log("keyMap", keyMap)
I'm trying to get the path until a tag with no tags and then set that path as value for the ID and then push the items 'own' title. But somehow the paths get messed up.
Check this, makePaths arguments are tags, result object and prefixed titles.
const makePaths = (tags, res = {}, prefix = []) => {
tags.forEach(tag => {
const values = [...prefix, tag.title];
Object.assign(res, { [tag.id]: values });
if (tag.tags) {
makePaths(tag.tags, res, values);
}
});
return res;
};
const tags = [
{
title: "Wood",
id: "dkgkeixn",
tags: [
{
title: "Material",
id: "ewyherer"
},
{
title: "Construction",
id: "cchtfyjf"
}
]
},
{
title: "Steel",
id: "drftgycs",
tags: [
{
title: "Surface",
id: "sfkstewc",
tags: [
{
title: "Polished",
id: "vbraurff"
},
{
title: "Coated",
id: "sdusfgsf"
}
]
},
{
title: "Quality",
id: "zsasyewe"
}
]
}
];
console.log(makePaths(tags));

How do i search 'titles' from array of objects & return only objects that match searchTerm?

bit of a newbie! I am trying to re-populate a carousel of images... based on an array of search results. But really hitting surprising amount of issues.
I'm using JS/Jquery and have, say, an array of objects that exist from my api:
let arrayOfObjects = [
{id: 0, title: 'Beauty & The Beast', img: 'https://imgthing1.com' },
{id: 1, title: 'The Brainiac', img: 'https://imgthing2.com' },
{id: 2, title: 'Mac and Me', img: 'https://imgthing3.com' }
];
Then i have my searchTerm which i want to filter the array down, and return a new array of results from:-
function checkWords(searchTerm, arr) {
let results = [];
let st = searchTerm.toLowerCase();
// **** i map through the array - if the search term (say its 'a' is the same
// as the first character of an object's 'title'... then it stores
// that object in results, ready to be rendered. ****
arr.map((each) => {
if (st === each.title.charAt(0)) {
results.push(each)
}
})
console.log(finalResults);
}
But i can't work out how to keep it matching... based on:
'Bea' vs 'Beauty & The Beast' - pass.
'Beat' vs 'Beauty & The Beast' - fail.
You could use Array#filter and check if the string contains the wanted string at position zero.
let arrayOfObjects = [{ id: 0, title: 'Beauty & The Beast', img: 'https://imgthing1.com' }, { id: 1, title: 'The Brainiac', img: 'https://imgthing2.com' }, { id: 2, title: 'Mac and Me', img: 'https://imgthing3.com' }];
function checkWords(searchTerm, arr) {
let st = searchTerm.toLowerCase();
return arr.filter(each => each.title.toLowerCase().indexOf(st) === 0);
}
console.log(checkWords('bea', arrayOfObjects));

Typescript update array value where index = value

i got this array :
array={
posts:[
{
isReported:false,
id:1,
title:'عنوان المقال القادم من الخادم رقم 1',
img:'assets/img/1.jpg',
userId:31,
userName:'محمود عبد السلام',
userImg:'assets/img/1.jpg'
},
....
],
....
}
i want to edit value of isReported for example where id = 3 and set it to true.
how to do this?
(function() {
const data = {
posts: [{
isReported: false,
id: 1,
title: 'عنوان المقال القادم من الخادم رقم 1',
img: 'assets/img/1.jpg',
userId: 31,
userName: 'محمود عبد السلام',
userImg: 'assets/img/1.jpg'
}, {
isReported: false,
id: 2,
title: 'عنوان المقال القادم من الخادم رقم 1',
img: 'assets/img/1.jpg',
userId: 31,
userName: 'محمود عبد السلام',
userImg: 'assets/img/1.jpg'
}, {
isReported: false,
id: 3,
title: 'عنوان المقال القادم من الخادم رقم 1',
img: 'assets/img/1.jpg',
userId: 31,
userName: 'محمود عبد السلام',
userImg: 'assets/img/1.jpg'
}]
};
const post3 = data.posts.filter(post => post.id === 3)[0];
if (post3) {
console.log(post3);
post3.isReported = true;
console.log(post3);
}
}());
Note, I renamed array to data since it is not an array but rather an object with an a property called posts that we access.
We use the filter method (Array.prototype.filter) to find the items in the array that we are interested in.
Since filter returns an array we access the first element.
If filter does not find any matching items, it returns an empty array and accessing the first element will return undefined so we check it before operating on it.
In newer runtimes we can express this more directly with the find method
const post3 = data.posts.find(post => post.id === 3);
you can do something like this:
array.posts.filter(item= > item.id === 3)[0].isReported = true;

Picking and merging JavaScript arrays

I have a data set that looks like this:
[
{
ProductID: 1,
ProductName: 'MyProduct',
Description: '.. some text here ..',
UnwantedData: 'garbage here'
},
{
ProductID: 2,
ProductName: 'MyOtherProduct',
Description: '.. some text here ..',
UnwantedData: 'garbage herAe',
GarbageField: '.. lorem ipsum ..'
}
]
I also have a reference array that looks like this:
[
{
name: 'ProductId',
map_to: 'item_id',
},
{
name: 'ProductName',
map_to: 'item_name',
},
{
name: 'Description',
map_to: 'description',
},
]
What I want to do is use that reference array to basically drop the "unwanted" data (ie. the properties that aren't names in the reference array) and replace the keys with whatever it's supposed to be mapped to (ie. ProductId->item_id).
The resulting array should look like this:
[
{
item_id: 1,
item_name: 'MyProduct',
description: '.. some text here ..'
},
{
item_id: 2,
item_name: 'MyOtherProduct',
description: '.. some text here ..'
}
]
What I've done so far
Given that ref is the reference array and data is the list of products.
var only = _.map( ref, 'name' );
var products = [];
async.eachLimit( data, 20, function(item, cb) {
products.push( _.pick(item, only) );
cb();
}, function(err) {
// .. then I iterate over the products array and manually replace each property
// I haven't done this yet
});
This code should work, but it feels a little inefficient and I want to know if there's a better way in achieving the desired resulting array since I'm going to be storing these in MongoDB.
Can anyone shed some light here?
You can try for loops:
var result = [];
for(var i=0; i<data.length; ++i) {
result[i] = {};
for(var j=0; j<ref.length; ++j)
result[i][ref[j].map_to] = data[i][ref[j].name];
}
var data = [
{
ProductID: 1,
ProductName: 'MyProduct',
Description: '.. some text here ..',
UnwantedData: 'garbage here'
}, {
ProductID: 2,
ProductName: 'MyOtherProduct',
Description: '.. some text here ..',
UnwantedData: 'garbage herAe',
GarbageField: '.. lorem ipsum ..'
}
];
var ref = [
{
name: 'ProductID',
map_to: 'item_id',
}, {
name: 'ProductName',
map_to: 'item_name',
}, {
name: 'Description',
map_to: 'description',
},
];
var result = [];
for(var i=0; i<data.length; ++i) {
result[i] = {};
for(var j=0; j<ref.length; ++j)
result[i][ref[j].map_to] = data[i][ref[j].name];
}
console.log(result);
Or, with ES5 array methods,
data.map(function(old) {
return ref.reduce(function(obj, assoc) {
obj[assoc.map_to] = old[assoc.name];
return obj;
}, {});
});
var data = [
{
ProductID: 1,
ProductName: 'MyProduct',
Description: '.. some text here ..',
UnwantedData: 'garbage here'
}, {
ProductID: 2,
ProductName: 'MyOtherProduct',
Description: '.. some text here ..',
UnwantedData: 'garbage herAe',
GarbageField: '.. lorem ipsum ..'
}
];
var ref = [
{
name: 'ProductID',
map_to: 'item_id',
}, {
name: 'ProductName',
map_to: 'item_name',
}, {
name: 'Description',
map_to: 'description',
},
];
console.log(data.map(function(old) {
return ref.reduce(function(obj, assoc) {
obj[assoc.map_to] = old[assoc.name];
return obj;
}, {});
}));
I usually find it easier to split objects into pairs with _.pairs, operate on the pairs, then turn them back into an object with _.object:
function goodPair(product_pair) {
var k = product_pair[0];
return refmap[k] != null;
}
function fixPair(product_pair) {
var k = product_pair[0];
var v = product_pair[1];
return [refmap[k], v];
}
function trimProduct(full_product) {
return _.object(_.pairs(full_product)
.filter(goodPair)
.map(fixPair));
}
console.log(data.map(trimProduct));
This way you can turn the entire transformation into one synchronous map over your product array.
Note that this is using a slightly simplified version of your ref here as refmap
var refmap = _.object(ref.map(function(r) {
return [r.name, r.map_to];
}));
// OR
var refmap = {
'ProductId': 'item_id',
'ProductName': 'item_name',
'Description': 'description',
};
I would use map() and transform() for this:
_.map(data, function(item) {
return _.transform(ref, function(result, r) {
result[r.map_to] = item[r.name];
}, {});
});
You're mapping your data to a new structure. Each new item is the result of transforming the ref item. The map_to key in the new object gets the name value in the original collection.

Categories

Resources