简体   繁体   中英

Create an array of specific elements from another array?

I have an array that can't be changed in terms of the element positions:

var array = ['item1', 'section1', 'section2', 'section3', 'section4', 'section5', 'prod1', 'prod2']

I want to make a new array from 'array' that takes the elements from position 1 - 5 (so all the section elements). It needs to be by position as the section elements make change by name.

var array2=array.slice(1,6)

See here for more information.

let's say we have an array like this

 const FILES_WITH_10_ASSETS = [
  '../assets/uploads/Desktop-300x600.jpeg',
  '../assets/uploads/Desktop-728x90.png',
  '../assets/uploads/Mobile-160x600.jpeg',
  '../assets/uploads/Mobile-300X50.jpeg',
  '../assets/uploads/Mobile-320x50.jpeg',
  '../assets/uploads/Mobile-320x480.jpeg',
  '../assets/uploads/Mobile-1024x768.jpeg',
  '../assets/uploads/Tablet-300x250.jpeg',
  '../assets/uploads/Tablet-Interstitial-320x480.gif',
  '../assets/uploads/Tablet-Interstitial-320x480.jpeg'
];

now we want some specific items from an array, we will create a function for this, here I have stored the function in an constant for further use

const SELECT_ASSETS = function(assetName: string) {
  let filtered_assets: string[] = [];
  for (let i in FILES_WITH_10_ASSETS) {
    if (FILES_WITH_10_ASSETS[i].includes(assetName) === true) {
      filtered_assets.push(FILES_WITH_10_ASSETS[i]);
    }
  }
  return filtered_assets;
};

and we call the method like this in our file

const ASSETS_NAME = SELECT_ASSETS(ASSET_NAME);

now we can pass the assets name to any function or method, if we pass the ASSET_NAME as Tablet we will get all three tablet paths, or if we change it to Mobile, we will get all five Mobile paths

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM